DEV Community

Cover image for Code Splitting in React
Shish Singh
Shish Singh

Posted on

Code Splitting in React

Introduction

In the ever-evolving landscape of web development, optimizing the performance of your React JS applications is paramount. Imagine a scenario where your application's bundle size is minimized, initial load times are slashed, and user experiences are elevated to new heights. This is precisely where the art of code splitting enters the stage.

Lazy Loading with lazy(): Gone are the days of loading entire scripts upfront, slowing down the initial user experience. With the lazy() function, React enables you to load components only when they're actually needed. We'll unravel the mysteries of this dynamic method, understand its syntax, and witness how it dramatically impacts load times.

Embracing Suspense: Imagine creating suspense not just in movies, but also in your application's loading behavior. Suspense allows you to gracefully manage asynchronous rendering and loading states, resulting in smoother transitions and reduced time-to-interactivity. We'll learn how to implement Suspense to its full potential, optimising user engagement and experience.

Crafting Fallback UIs:While code splitting and lazy loading enhance your application's speed, what happens if something goes awry? Fallback UIs step in as a safety net, ensuring users are met with a visually pleasing and informative interface even when components fail to load. We'll explore strategies to design elegant fallbacks, preserving user satisfaction in the face of loading uncertainties.

Comprehension

As our web app grows, the javascript bundle size increase. To avoid larger javascript bundle we can use the concept of splitting.
In react, there is a feature to support code splitting and lazy loading. It allows dynamic imports on the react components using lazy() function. For the dynamically imported components, we can wrap them in the suspense component to show a fallback UI while we wait for the component to load.

import React, {Suspense, lazy} from 'react';
const NavB= lazy(()=> import('./navB'));
function Page(){

return (
  <div>
    <Suspense fallback={<div>Loading...</div>}>
      <NavB/>
    </Suspense>
  </div>
);

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)