How would you code split routes in a React app using React Router?
Short answer
Each page in a router setup can be wrapped in React.lazy, so that visiting the home page does not force the browser to also download the code for the about page or the contact page. This is one of the most common and effective places to add code splitting in a real app.
Advertisement
AModel answer
Each page in a router setup can be wrapped in React.lazy, so that visiting the home page does not force the browser to also download the code for the about page or the contact page. This is one of the most common and effective places to add code splitting in a real app.
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
function AppRoutes() {
return (
<Suspense fallback={<p>Loading page</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
);
}Real-world example
A company website with ten different pages splits each page into its own file, so a first time visitor loading the home page only downloads the code for that one page, not all ten.
Likely follow-ups
- Should every single route always be code split, even very small pages?
- How does this affect how fast a user can navigate between two already visited pages?
Related topics