← React Beginner Questions - Set 3 Q26

What is lazy loading in React?

React Beginner Questions - Set 3

Split the bundle so a route or a heavy widget is downloaded on demand instead of at startup.

Example

import { lazy, Suspense, useState } from 'react';
import { Routes, Route } from 'react-router-dom';

// The import only happens when the component first renders
const Reports = lazy(() => import('./pages/Reports'));

export default function App() {
  const [show, setShow] = useState(false);

  return (
    <>
      <button onClick={() => setShow(true)}>Open reports</button>
      <Suspense fallback={<p>Loading module…</p>}>
        {show && <Reports />}
      </Suspense>
      <Routes>
        <Route path="/reports" element={
          <Suspense fallback={<p>Loading…</p>}><Reports /></Suspense>
        } />
      </Routes>
    </>
  );
}

What to notice

← Back to the question list