Code Splitting
Loading "Intro to Code Splitting"
Run locally for transcripts
Code splitting acts on the principle that loading less code will speed up your
app. Say for example that we're building a complex dashboard application that
includes the venerable d3 library for graphing data. Your users start
complaining because it takes too long to load the login screen.
So, considering that performance problems can be resolved by less code, how can we
solve this one? Well, do we really need to have that code for the chart when
the user loads the login screen? Nope! We could load that on-demand.
Luckily for us, there's a built-in way to do this with JavaScript standards.
It's called a dynamic import and the syntax looks like this:
import('/some-module.js').then(
(module) => {
// do stuff with the module's exports
},
(error) => {
// there was some error loading the module...
},
)
๐ Learn more about dynamic imports in the browser in Super Simple Start to ESModules in the browser
To take this further, React has built-in support for loading modules as React
components. The module must have a React component as the default export, and
you have to use the
<Suspense />
component to render a fallback value while
the user waits for the module to be loaded.// smiley-face.tsx
export default function SmileyFace() {
return <div>๐</div>
}
// app.tsx
import { lazy, Suspense } from 'react'
const SmileyFace = lazy(() => import('./smiley-face.tsx'))
function App() {
return (
<div>
<Suspense fallback={<div>loading...</div>}>
<SmileyFace />
</Suspense>
</div>
)
}
๐ฆ One great way to analyze your app to determine the need/benefit of code
splitting for a certain feature/page/interaction, is to use
the "Coverage" feature of the developer tools.