Introducing Code Splitting to a React Web App

A Noob Meets Web Apps, Episode 6

Marco Muccinelli

--

In previous episode we introduced routing. App starts to have a structure: I’ll try to run a production build to evaluate code size.

$ npm run build

Code splitting

Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code in your app, you’ve avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.
https://reactjs.org/docs/code-splitting.html#code-splitting

React provides out of the box solution for code splitting: React.lazy(): let’s test it with highlighted polls. I convert HighlighedPolls.route() to use a lazily loaded component.

Because React.lazy only works with default exports, I convert named export in features/highlightedPolls/component.tsx:

Changes to route.tsx are straighforward:

I used same strategy also in features/poll/route.tsx, then I changed imports in App.tsx not to include actual components via module:

If you make a new production build, you will observe a new chunk has been created.

Split out Firebase

I take a guess: Firebase library can be splitted to slim down code size. To do so I will create a new component in app/features/Firebase.tsx:

Code inside App.tsx will be very reduced: no Firebase imports, no authentication state.

Suspense

But it doesn’t work. If you try to reload you will get error:

A React component suspended while rendering, but no fallback UI was specified. Add a <Suspense fallback=…> component higher in the tree to provide a loading indicator or placeholder to display.

I admit it’s crystal clear and solution is pretty simple:

Another production build will result in a few more chunks:

--

--