React માં Lazy Loading

મોટી React એપ્સ મોટા JavaScript બંડલ્સ બનાવે છે. મોટા બંડલ્સ તમારી સાઇટને ધીમી બનાવે છે. યુઝર્સ તમારી એપ સાથે ઇન્ટરેક્ટ કરવા માટે વધુ સમય રાહ જુએ છે. આ તમારા યુઝર એક્સપિરિયન્સને નુકસાન પહોંચાડે છે.

Lazy loading આ સમસ્યાનું સમાધાન કરે છે. તે components ને ત્યારે જ લોડ કરે છે જ્યારે યુઝર્સને તેમની જરૂર હોય. તમે બધું એકસાથે લોડ કરવાનું બંધ કરો છો.

Lazy loading ના ફાયદા:

React.lazy() નો ઉપયોગ કેવી રીતે કરવો React components ને ડાયનેમિકલી ઇમ્પોર્ટ કરવા માટે lazy() નામનું ફંક્શન પૂરું પાડે છે. React કોડને ત્યારે જ ડાઉનલોડ કરે છે જ્યારે તે component ને render કરે છે.

ઉદાહરણ કોડ: import { lazy } from "react";

const ProductDetail = lazy(() => import("./pages/ProductDetail"));

તમારે lazy components સાથે Suspense નો ઉપયોગ કરવો જ પડશે. જ્યારે component લોડ થઈ રહ્યો હોય ત્યારે Suspense એક fallback UI બતાવે છે.

ઉદાહરણ કોડ: import { Suspense, lazy } from "react";

const ProductDetail = lazy(() => import("./pages/ProductDetail"));

function App() { return ( <Suspense fallback={

Loading...
}> ); }

સફળતા માટેના બે નિયમો:

  • તમારા components માં default exports નો ઉપયોગ થવો જોઈએ.
  • તમારા lazy imports ને તમારા component functions ની બહાર જાહેર કરો.

શું તમે તમારા પ્રોજેક્ટ્સમાં lazy loading નો ઉપયોગ કરો છો? નીચે કોમેન્ટ કરો. હું તમને જવાબ આપીશ.

સ્ત્રોત: https://dev.to/madhubankhatri/lazy-loading-in-react-improve-performance-with-reactlazy-and-suspense-5edk