← Back to React Course | Chapter 13: Advanced React & Architecture | Lesson 5 of 14

React.lazy से Code Splitting

React.lazy के साथ code splitting सिर्फ उस country के लिए suitcase पैक करने जैसा है जहां आप अभी जा रहे हैं, बजाय इसके कि आप हर country के लिए luggage carry करें जहां आप कभी जा सकते हैं।
Syntax
markup
const LazyComponent = React.lazy(() => import("./LazyComponent"));

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

React.lazy से Code Split करना

React.lazy() एक function लेता है जो dynamic import() syntax call करता है, उस component के module के लिए एक Promise return करते हुए। Bundler (Vite, webpack) अपने आप उस component को अपनी separate file में split करता है, जो runtime पर सिर्फ तभी download होती है जब इसकी असल में ज़रूरत हो।

Note: यह बड़े components या पूरे routes के लिए सबसे valuable है जो बहुत पहले page load पर ज़रूरी नहीं हैं, जैसे एक settings page या एक admin panel।
Warning: React.lazy की imported function को एक default export वाले object में resolve होना चाहिए — सिर्फ एक named export React.lazy के साथ directly काम नहीं करेगा।

उदाहरण: Splitting Code with React.lazy

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
const LazySettings = React.lazy(() =>
  Promise.resolve({ default: () => <p>Settings page (loaded on demand)</p> })
);
function App() {
  const [show, setShow] = React.useState(false);
  return (
    <div>
      <button onClick={() => setShow(true)}>Load Settings</button>
      {show && <React.Suspense fallback={<p>Loading settings...</p>}><LazySettings /></React.Suspense>}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Routes को Lazy Load करना

React.lazy के सबसे common और impactful uses में से एक per-route code splitting है: आपके app का हर page अपना chunk बन जाता है, इसलिए सिर्फ homepage देखने वाला user उस admin dashboard या settings page का code कभी download नहीं करता जिसे वह कभी visit नहीं करता।

Note: इसे React Router के Route element prop के साथ combine करें — हर lazy-loaded page component फिर भी normally plug in होता है।
Warning: हर lazy-loaded route को tree में कहीं Suspense में wrap होना चाहिए (अक्सर एक बार, पूरे Routes block के around) — इसे भूल जाना उस route पर navigation तोड़ देता है।

उदाहरण: Lazy Loading Routes

markup
// Run in your local React project (npm install required)
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));

function AppRoutes() {
  return (
    <Suspense fallback={<p>Loading page...</p>}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/settings" element={<Settings />} />
      </Routes>
    </Suspense>
  );
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Loading Flash Tradeoff को Weigh करना

Lazy loading एक छोटे initial bundle के बदले एक brief loading state trade करता है जब पहली बार एक particular chunk की ज़रूरत हो। जिन components की हमेशा तुरंत ज़रूरत होती है (जैसे main navigation), यह tradeoff worth नहीं है — loading flash उस specific piece के लिए किसी real bundle-size benefit के बिना सिर्फ friction जोड़ता है।

Note: Lazy loading उन चीज़ों के लिए reserve करें जिनकी पहले render पर immediately ज़रूरत नहीं है — हमेशा-visible layout pieces main bundle में रहने चाहिए।
Warning: कुछ ऐसा lazy-load करना जो हमेशा immediately visible हो सिर्फ एक unnecessary loading flicker जोड़ता है बिना किसी actual performance win के।

उदाहरण: Weighing the Loading Flash Tradeoff

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
// Good candidate: rarely visited, large feature
const AdminPanel = React.lazy(() => Promise.resolve({ default: () => <p>Admin</p> }));

// Poor candidate: always visible immediately -- keep this in the main bundle
function MainNav() { return <nav>Always here, no lazy loading needed</nav>; }
function App() { return <MainNav />; }
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि React.lazy को हमेशा इसे wrap करती एक Suspense boundary के साथ paired होना चाहिए, वरना यह एक error throw करता है।
  2. उन components को lazy-load करना जिनकी हमेशा तुरंत ज़रूरत होती है (जैसे main layout), बिना किसी benefit के एक unnecessary loading flash जोड़ते हुए।
  3. Dynamic import() function को एक default export वाले module में return होना चाहिए — React.lazy named exports को directly support नहीं करता।
चैप्टर सारांश
  • React.lazy(() => import('./Component')) एक component को इसके अपने separate JS chunk में split करता है, सिर्फ ज़रूरत पड़ने पर loaded।
  • यह initial bundle size कम करता है, app की first-load performance बेहतर करते हुए।
  • एक lazy component को हमेशा एक fallback वाली Suspense boundary के अंदर render होना चाहिए।
  • Lazy loading के लिए अच्छे candidates: routes, modals, और rarely-used features जिनकी first render पर ज़रूरत नहीं है।
ब्राउज़र सपोर्ट

React.lazy React 16.6 से available है; bundler (Vite/webpack) के dynamic import() support करने पर निर्भर करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.