Taking the Economical Approach: Code-Splitting in React

React Logo

One of the predominant concerns of front-engineering is the achievement of optimal performance in an application. Decisions — both on a structural level and on a code level — are made with this in mind. One of the reasons why React is so popular with engineers and businesses is that it encompasses a wide range of features that enable performance optimisation. These include the library’s light weight, its broad suite of built-in hooks and memoisation, to name just a few.

One feature of React which is very effective in providing optimisation of performance is its built-in code-splitting feature.

Dynamic Imports

Code-Splitting

Instead of statically importing all required modules at the beginning of a file (which are then included in the bundled JavaScript file), a component can be imported inside of the execution of a function. Thus, it will not be downloaded to the browser unless the function is called.

React.lazy()

const dynamicallyImportedComponent = React.lazy(() => import('./component'));

Since a dynamic import returns a promise, the component which is carrying out the dynamic import must handle its pending state. It does this by wrapping the imported component inside of React’s Suspense component (see my article on React’s Suspense component here). Suspense enables lazy loading of data by rendering a fallback element until the data — in this case the dynamically imported component — is loaded. Indeed, multiple dynamically imported components may be included within the Suspense component.

Route-Based Code-Splitting

In order to implement this route-based code-splitting, page components are dynamically imported inside of aSuspense component, which is in turn contained within the React Router component.

Conclusion

JavaScript Enthusiast and Professional