React Router enables lazy loading of components by leveraging React's React.lazy() and Suspense components. Below are the basic steps to implement lazy loading with React Router:
- Implementing Dynamic Imports with
React.lazy:React.lazy()is a function that allows you to dynamically load components. It enables you to define a component that is automatically loaded upon the first render.
jsxconst LazyComponent = React.lazy(() => import('./LazyComponent'));
- Wrapping Routes with
Suspense: In your application, you need to wrap the lazy-loaded routes with theSuspensecomponent.Suspenseallows you to specify a fallback indicator (such as a spinner) that is displayed while the lazy-loaded component is being loaded.
jsximport { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import React, { Suspense } from 'react'; const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/lazy" component={LazyComponent} /> {/* Other routes */} </Switch> </Suspense> </Router> ); }
- Creating Separate Chunks for Lazy-Loaded Components: When using
create-react-appor other build tools, it automatically generates a separate JavaScript chunk file for each component imported viaReact.lazy(). This means the code is only loaded when needed.
For example, suppose you have a large component BigComponent that you don't want to load initially when the app starts. Instead, you want it to load when the user accesses the corresponding route. You can set it up like this:
jsximport { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import React, { Suspense } from 'react'; const BigComponent = React.lazy(() => import('./BigComponent')); function App() { return ( <Router> <Suspense fallback={<div>Loading Big Component...</div>}> <Switch> <Route path="/big-component" component={BigComponent} /> {/* Other routes */} </Switch> </Suspense> </Router> ); }
In the above example, when the user visits the /big-component path, BigComponent is dynamically loaded. The user sees "Loading Big Component..." until BigComponent is loaded and ready to render. This reduces the initial load time of the application and loads resources on demand, improving performance.