Skip to content
react questions

React · 13 of 13middle~1 min

How does code splitting work in React and what tools enable it?

#performance#bundling

Code Splitting in React

Code splitting is breaking the bundle into pieces that load on demand (lazy loading).

React.lazy + Suspense

tsx
import { lazy, Suspense } from 'react'; const SettingsPage = lazy(() => import('./SettingsPage')); function App() { return ( <Suspense fallback={<PageSkeleton />}> <SettingsPage /> </Suspense> ); }

Route-based splitting (React Router)

tsx
const router = createBrowserRouter([ { path: '/', lazy: () => import('./HomePage') }, // module exports Component { path: '/dashboard', lazy: () => import('./DashboardPage') }, ]);

Tools

ToolMechanism
Webpackimport() - automatic chunks
ViteESM-based splitting out of the box
Next.jsAutomatic per page + dynamic()

Webpack magic comments

tsx
const Chart = lazy(() => import(/* webpackChunkName: "chart" */ './Chart') );

Goal: send the user only the code needed for the current screen.

updated

did you know it?

read more on the blog

view all

related questions