[React] Route-based Splitting
Source: https://javascriptpatterns.vercel.app/patterns/performance-patterns/route-based-splitting
If you're using react-router
for navigation, you can wrap the Switch
component in a React.Suspense
, and import the routes using React.lazy
. This automatically enables route-based code splitting.
import React, { lazy, Suspense } from "react";
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
const App = lazy(() => import("./App"));
const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));
ReactDOM.render(
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/">
<App />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</Suspense>
</Router>,
document.getElementById("root")