Code Splitting For React Developers

Performance is a very important factor in software development and bundling our files increases “Cost of Performance ” especially when the application gets bigger.

These can be seen in some cases where we have to install some third-party libraries that end up being bundled even when they are not needed on page load.

Here is an example of a page load with unused Bytes of dataLooking at the coverage of a typical React Page above, you will notice that over 68% of “bundle.

js” was not needed at the time yet it was loaded and this gets to rub off on the performance of our app as it gets bigger.

Issues like this necessitated the concept of code splitting.

Implementing Code-splitting in ReactCode splitting which is also supported by our favorite Webpack and Browserify helps us to load those things that are needed by our app on page load first, then load the rest based on the need or use case of the user, which will go a long way in optimization and overall improvement of our app.

This process of our app loading only the needed files for initial page load is called “Lazy-loading”.

React has a function call “React.

lazy()” that make it possible to render dynamic imports as regular components.

Here is our regular way of importing componentsUsing React.

lazy() for code splittingUsing React.

lazy() for code splitting as shown in the above code snippet is not totally error-proof as we are likely to get an error if the second component is still loading while the first component has been rendered, but not to worry, React got your back with a handy component called “Suspense”.

Suspense is a component that accepts a fallback prop that can be rendered while your component is still loading and this can easily be achieved by wrapping your lazy loaded components with Suspense as shown below.

wrapping Lazy-loaded components with Suspense provides a fallback while they are loadingthe code snippet above shows how easy it is to achieve code splitting with React lazy-loading and Suspense which apart from optimization and performance improvement, also gives the user a modern experience by not showing a blank page during page load.

ConclusionAs people’s attention span continues to reduce, it is a big disadvantage to tolerate a page load of more than 3 seconds for first-time users, hence the need to take web performance very serious during development.

With React lazy loading and Suspense it is possible to reduce page load time to the barest minimum while keeping the page busy for the users during load-time.

It will also be worthy of note that the concept of React lazy loading and Suspense are not yet available server-side rendering as at the time of this publication, but similar aim can be achieved using loadable components.

For Questions, feel free to hola via twitter @w3bh4ck.

. More details

Leave a Reply