πΏ Lazy loading
Jorjis Hasan
Posted on February 5, 2024
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 πΏ
Steps: Implement Lazy loading
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:
//app.js
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"));
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 />
</Suspense>
Posted on February 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.