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
- What does
React.Suspense
render while a lazy component is loading? - How does
React.lazy
help with performance?
Show answers
- The
fallback
element you provide (e.g., a loading spinner or skeleton). - It code-splits components so they load on demand, reducing initial bundle size.
Exercises
- Replace the simulated Promise with a real dynamic import:
React.lazy(() => import('./LazyHello.js'))
. - Show a skeleton UI instead of text while loading.
- Measure load time before and after lazy loading to observe the impact.