Code Splitting

What is code splitting?

→ Don’t download code until the user needs it.


You can’t dynamically import or export, it is static. They have to be defined on compile time not runtime.



This would be super convenient but it is not allowed in JS, it wouldnt’ work.


However, you can do the following on create-react-app and soon on JS (stage 4):


React Lazy


Lets you render a dynamic import as a regular component.



You can use that mental model for any component import in your app. A common pattern is to do it on a route level, so you only download the code for the section of the app you are in. But you could do it anywhere, i.e: you have a page with a hidden modal that loads a heavy chart, you only need that chart if the modal is rendered, so maybe lazy load the component?


Only thing to remember is that if you use React.lazy, you’ll need to wrap your lazy loaded components in a React.Suspense and give it a fallback to render while it loads.


You can see an example of route lazy loading in action here:

React.lazy - CodeSandbox

React.lazy - CodeSandbox

Notes


foo in this case is a Promise.


foo in this case is a React Component.



Copyright 2023 © Borja Leiva

Made within London