35. Code Splitting
Shrinking the Bundle Size
When you build a React app, tools like Vite or Webpack package all of your components, libraries, and logic into one massive JavaScript file (the "Bundle"). If a user visits your homepage, they shouldn't have to download the code for the Admin Settings page. Code Splitting divides your app into smaller chunks, loading them only when needed.
React.lazy() and Dynamic Imports
We implement code splitting using React.lazy(). Instead of importing a component normally at the top of the file, we tell React to fetch the component's file dynamically over the network only when it is about to be rendered.
The <Suspense> Boundary
Because the lazy-loaded component is fetched over the network, there will be a slight delay. React requires you to wrap lazy components in a <Suspense> boundary. The fallback prop tells React what to display while the code is downloading.
Route-Based Code Splitting
The most effective place to use Code Splitting is at the route level. By lazy-loading your page components in React Router, you guarantee users only download the specific page they navigate to.
Knowledge Check
Ready to test your understanding of 35. Code Splitting?