Lazy Loading Components in React

 ⚡️ Lazy Loading Components in React

✅ What is Lazy Loading?

Lazy loading means loading parts of your application only when they are needed, instead of loading everything up front. In React, this is often used to improve performance by loading components on demand.


๐Ÿง  Why Use Lazy Loading?

✅ Reduces the initial load time of your app


✅ Improves performance, especially for large apps


✅ Saves bandwidth by loading only what the user needs


๐Ÿ›  How to Lazy Load a Component in React

React provides a built-in function called React.lazy() for lazy loading.


๐Ÿ“ฆ Example

Suppose you have a component called Profile.js.


✅ Step 1: Use React.lazy()

javascript

Copy

Edit

import React, { Suspense } from 'react';


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

✅ Step 2: Wrap it in <Suspense>

javascript

Copy

Edit

function App() {

  return (

    <div>

      <h1>Welcome!</h1>

      <Suspense fallback={<div>Loading...</div>}>

        <Profile />

      </Suspense>

    </div>

  );

}

๐Ÿ”น The fallback prop is what the user sees while the component is loading (like a spinner or message).


๐ŸŽฏ Best Practices

✅ Use lazy loading for routes or large components.


❌ Don’t overuse it for small or frequently used components.


✅ Combine with code splitting (e.g., React Router) for maximum benefit.


๐ŸŒ Lazy Loading with React Router (v6+)

javascript

Copy

Edit

import { lazy, Suspense } from 'react';

import { BrowserRouter, Routes, Route } from 'react-router-dom';


const Home = lazy(() => import('./pages/Home'));

const About = lazy(() => import('./pages/About'));


function App() {

  return (

    <BrowserRouter>

      <Suspense fallback={<p>Loading page...</p>}>

        <Routes>

          <Route path="/" element={<Home />} />

          <Route path="/about" element={<About />} />

        </Routes>

      </Suspense>

    </BrowserRouter>

  );

}

๐Ÿงช Lazy Loading Tips

Tip Description

✅ Error Boundaries Use them to catch loading errors

๐Ÿšซ No SSR support React.lazy() doesn’t work with server-side rendering

๐Ÿš€ Preload if needed Use import().then() to preload components before they’re needed

Learn MERN Stack Course in Hyderabad

Read More

React State Management Best Practices

๐ŸŽจ Frontend (React Focused)

Building a File Upload API in MERN

Setting Up WebSockets with Node and Express

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners

Why Data Science Course?