What is Lazy Loading?
By default, React bundles your entire application into one large JavaScript file. As your app grows, this file becomes heavy, leading to slow initial load times. Lazy loading (or code splitting) allows you to break your app into smaller chunks and load them only when the user actually navigates to that part of the application.
Using React.lazy and Suspense
The React.lazy function lets you render a dynamic import as a regular component. It must be rendered inside a <Suspense> component, which allows you to show a fallback UI (like a loading spinner) while the lazy component is being fetched.
Route-Based Code Splitting
The most common place to implement lazy loading is at the route level. This ensures that users only download the code for the page they are currently visiting.
When to Use Lazy Loading
- Routes: Every major page in your app should likely be lazy-loaded.
- Heavy Libraries: Components that use large libraries like D3.js, Three.js, or complex editors.
- Modals and Dialogs: Components that only appear after a user interaction (like clicking a 'Help' button).
- Conditional Content: Sections of a page that are hidden behind tabs or accordions.
Error Boundaries with Lazy Loading
If a network error occurs while fetching a lazy component (e.g., the user loses internet), the app will crash unless you wrap the Suspense block in an Error Boundary. This allows you to show a 'Network Error' UI instead of a blank screen.