DEV Community

Cover image for 🍿 Lazy loading
Jorjis Hasan
Jorjis Hasan

Posted on

🍿 Lazy loading

An essential task of bundler(vite, webpack, parcel) is bundling. What does that mean? This means it takes all the files and bundles all of them into one big ass file. What's the problem then? The problem is that the size of that one file will significantly increase. The app will be very slow as the development build is involved.

So, how to tackle this issue? We need to break down our app into smaller logical chunks. How to make smaller bundles and when to make them? What should be there is a small bundle? If I do logical separation, Over here in makemytrip, it is very clear that I can make components just for my flights, Homestays, Hotels, and Holidays.

A bundle should have enough features for the central part of our app. How to do that? There are different names for this concept. This (Lazy loading) process is also known as

  • Chunking
  • Lazy Loading
  • Code Splitting
  • Dynamic import
  • Dynamic bundling
  • On-demand Loading

These are the same thing.

Problem: Suppose our app has home, about, and contact components. The home component loads when the initial render happens. Nothing special! But, the app requires a particular functionality: the about and contact components will be rendered only when requested.

Solution: Lazy Loading 🍿

Problem Visualization

See the full code →

Steps: Implement Lazy loading

  1. lazy()
  2. < Suspense >

Step 1:
We don't use the traditional import approach when we import those two components(about contact). Rather, we'll do something like this:

import React, { lazy} from "react";

import About from "./components/About";
import Contact from "./components/Contact";

const About = lazy(() => import("./components/About"));
const Contact = lazy(() => import("./components/Contact"));
Enter fullscreen mode Exit fullscreen mode

Step 2:
<Suspense> lets you display a fallback until its children have finished loading. If you don't use it then react will throw you an error. Wherever we invoke a lazy loading component, we must wrap that into <Suspense> Just like this:

<Suspense fallback={"Loading..."}>
  <About />
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

maya_walk profile image
Maya Walker

Lazy loading it's vacation

jorjishasan profile image
Jorjis Hasan

Enjoy buddy 🍿

get_pieces profile image
Pieces 🌟

Great article! 🔥

_ndeyefatoudiop profile image
Ndeye Fatou Diop

Very nice ! What I also like to do is pass in a webpackChunkName like in here so the chunks are easier to find

jorjishasan profile image
Jorjis Hasan

Well, that's a nicer approach along with Webpack 👏

iamprahlad profile image

awesome share

jitendrachoudhary profile image
Jitendra Choudhary

Clean Explanation

jorjishasan profile image
Jorjis Hasan

Glad You liked it !