Route based code splitting in react

Amit Kumar
2 min readFeb 4, 2023

--

Route-based code splitting is a technique used in React applications to only load the code for a specific route or page when it is needed. This can help to improve the performance of the application by reducing the initial load time and the amount of JavaScript that needs to be downloaded.

This is done by using dynamic imports, which allows you to load a module only when it is needed, rather than including it in the initial bundle. In React, this can be done using the lazy function from the react-loadable library, which allows you to load a component as a separate module when a specific route is rendered.

For example, to code split a component called MyComponent that is rendered when the user navigates to the /my-route path, you would use the following code:

import React, { lazy, Suspense } from 'react'
const MyComponent = lazy(() => import('./MyComponent'))
function App() {
return (
<Suspense fallback={<div>Loading…</div>}>
<Router>
<Switch>
<Route path="/my-route">
<MyComponent />
</Route>
{/* Other routes */}
</Switch>
</Router>
</Suspense>
)
}

This will load the code for MyComponent only when the user navigates to the /my-route path, improving the initial load time of the application. Note that, we need to wrap the component with Suspense component as it is the component that will show loading while the component is being loaded.

--

--