Interested in our next book? Learn more about Building Large-scale JavaScript Web Apps with React

Route Based Splitting

We can request resources that are only needed for specific routes, by adding route-based splitting. By combining React Suspense or loadable-components with libraries such as react-router, we can dynamically load components based on the current route.

index.js
1import React, { lazy, Suspense } from "react";
2import { render } from "react-dom";
3import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
4
5const App = lazy(() => import(/* webpackChunkName: "home" */ "./App"));
6const Overview = lazy(() =>
7 import(/* webpackChunkName: "overview" */ "./Overview")
8);
9const Settings = lazy(() =>
10 import(/* webpackChunkName: "settings" */ "./Settings")
11);
12
13render(
14 <Router>
15 <Suspense fallback={<div>Loading...</div>}>
16 <Switch>
17 <Route exact path="/">
18 <App />
19 </Route>
20 <Route path="/overview">
21 <Overview />
22 </Route>
23 <Route path="/settings">
24 <Settings />
25 </Route>
26 </Switch>
27 </Suspense>
28 </Router>,
29 document.getElementById("root")
30);
31
32module.hot.accept();

By lazily loading the components per route, we’re only requesting the bundle that contains the code that’s necessary for the current route. Since most people are used to the fact that there may be some loading time during a redirect, it’s the perfect place to lazily load components!