What is code splitting and why do we need it in our React apps ?
This is a follow up article to An Introduction to React Suspense, there I explained the general idea around Suspense and it's pivotal you read that first as Suspense plays a key part in code splitting An Introduction to React Suspense. So what is code splitting ? Well think of it like this. Say we have a React app with 20+ routes, tons of components, lots of data fetching etc. That means you have a really big bundle when you build your app and that could make your app really slow and you don't want that do you ? Now we don't really need to load all that data do we ? There's say 5 routes you're a 100% sure the user will navigate to, the remaining? they might or might not so you don't need to load the data for those routes immediately do you ? Just lazy-load the data when the user navigates to the route. That is the basic idea behind code splitting. This can dynamically improve performance of your React apps (especially if coupled with memoization techniques). The easiest way to implement code splitting is via dynamic imports which returns a promise.
//example.js
export default exampleComponent=> 1 + 2;
import('./example.js).then(exampleComponent => console.log(exampleComponent))
Introducing React.lazy
Lazy per the React docs: "The React.lazy function lets you render a dynamic import as a regular component." It looks like this:
const {lazy} = React;
const ExampleComponent = lazy(()=> import('./example.js))
Now remember Suspense that I talked about in the previous article ? (link above if you haven't read it), in the render or return we pass ExampleComponent
as JSX between Suspense and remember I said dynamic imports returns a promise and as we know promises can either be resolved or rejected. If a condition is met i.e. the promise is resolved we render the component.
So that looks like this
<Suspense fallback={<p>Loading....</p>}>
<ExampleComponent/>
<Suspense/>
And that is how we implement code splitting in our React applications.