DEV Community

Cover image for React's Dynamic Trio: Code-Splitting Unleashed!
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

React's Dynamic Trio: Code-Splitting Unleashed!

In the ever-evolving world of web development, optimizing the performance of React applications is a paramount concern. Entering the realm of code splitting, I learned a technique that promises to transform the landscape by breaking down colossal React applications into nimble, on-demand modules. One of the stalwarts in this paradigm shift is the dynamic import feature, where asynchronous loading takes centre stage, paving the way for a faster and more responsive user experience.

In this track of innovation, we will explore the perfect sync. of Dynamic Imports, Lazy, and Suspense in React, unlocking the potential to elevate your application's speed and efficiency. Buckle up for a journey into the future of React development!

Code Splitting in React

Code splitting in React is a technique for breaking down a large React application into smaller bundles that can be loaded on demand or in parallel. This can improve the performance of the application by reducing the initial load time and avoiding loading code that is not needed immediately.

React provides several ways to achieve code splitting & one of the most common methods is by using dynamic imports with the help of Lazy and Suspense components.

Dynamic Imports

Dynamic imports are asynchronous, meaning they don't block your application's main thread. When you use import(), it returns a Promise immediately, and returns an object representing the module, allowing you to access both the default and named exports explicitly.

import("./mymodules.js")
   .then((module) => {
      const { default: defaultExp, namedExp1, namedExp2 } = module;

      console.log(defaultExp);
      // Output: This is a default export

      console.log(namedExp1, namedExp2);
      // Output: Named Export 1 Named Export 2
   })
   .catch((error) => {
      console.error("Error Loading module:", error);
   });
Enter fullscreen mode Exit fullscreen mode

Lazy and Suspense

Code splitting in React with Lazy and Suspence is a new way to split code into smaller bundles that can be loaded on demand. To use code splitting with lazy and suspense, you first need to identify the parts of your application that can be loaded on demand.

You can use the suspense component to specify a fallback UI displayed while the lazy-loaded component is loading.

Lazy() | Function

The lazy function takes a function as an argument, which will be called when the module is needed. The function should return a promise that resolves to the module

const MyComponent = Lazy(() => import("./MyComponent"));
Enter fullscreen mode Exit fullscreen mode

This code will import the MyComponent component asynchronously. To render a lazy loaded component, you can use the component.

<Suspense> | Component

React's Suspense component is used for asynchronous operations like lazy loading components with React.Lazy(), Lazy(), or data fetching with fetch(). It renders fallback content with fallback prop while waiting for the operation to complete.

import React, { Lazy, Suspense } from 'react';

const MyComponent = Lazy(() => import('./MyComponent'));

const App = () => {
   return (
      <div>
         <h1>My React App</h1>
         <Suspense fallback={<div>Loading...</div>}>
            <MyComponent />
         </Suspense>
      </div>
   );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In wrapping up, think of code splitting in React as a cool trio – dynamic imports, Lazy, and Suspense. They're like rockstars making your app faster and more impressive. It's not just a tech upgrade; it's your app becoming a quick and snappy hero. Cheers to this new way of loading stuff – it's a game-changer! 🚀

Happy Coding

Top comments (2)

Collapse
 
mzakiullahusman profile image
Muhammad Zakiullah Usman

in the snippet you shared at the end, is it combining lazy loading with dynamic imports?

Collapse
 
mursalfk profile image
Mursal Furqan Kumbhar

Yes, in the provided snippet, Lazy loading is implemented using the React.lazy function, which is combined with dynamic imports. The React.lazy function allows you to load a component lazily (i.e., only when it's actually needed) by providing a function that returns a dynamic import. The dynamic import is achieved through the use of the import() function.

Here's the relevant part of the snippet:

import React, { lazy, Suspense } from 'react';

const MyComponent = lazy(() => import('./MyComponent'));

const App = () => {
   return (
      <div>
         <h1>My React App</h1>
         <Suspense fallback={<div>Loading...</div>}>
            <MyComponent />
         </Suspense>
      </div>
   );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, MyComponent is lazily loaded using React.lazy(() => import('./MyComponent')), and the <Suspense> component is used to specify a fallback UI while the MyComponent is being loaded asynchronously.