React - Suspense & Lazy Loading

Overview

Estimated time: 15–25 minutes

Lazy load components to reduce initial bundle cost. Use React.Suspense to display a fallback while the component loads.

Try it: Simulated lazy component

View source
const LazyHello = React.lazy(() => new Promise(res => setTimeout(() => res({ default: () => <div>Hello from lazy component!</div> }), 800)));
function App(){
  const [show, setShow] = React.useState(false);
  return (
    <div>
      <button onClick={() => setShow(s => !s)}>{show ? 'Hide' : 'Show'} Lazy</button>
      <div style={{marginTop:8}}>
        <React.Suspense fallback={<div>Loading...</div>}>
          {show && <LazyHello />}
        </React.Suspense>
      </div>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-suspense')).render(<App />);

Syntax primer

  • React.lazy(() => import(...)) code-splits components; here we simulate with a Promise.
  • <Suspense fallback=...> shows a placeholder while loading.

Common pitfalls

  • Suspense for data fetching differs from lazy loading components; don’t conflate the two.

Checks for Understanding

  1. What does React.Suspense render while a lazy component is loading?
  2. How does React.lazy help with performance?
Show answers
  1. The fallback element you provide (e.g., a loading spinner or skeleton).
  2. It code-splits components so they load on demand, reducing initial bundle size.

Exercises

  1. Replace the simulated Promise with a real dynamic import: React.lazy(() => import('./LazyHello.js')).
  2. Show a skeleton UI instead of text while loading.
  3. Measure load time before and after lazy loading to observe the impact.