Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

How does Suspense work with lazy components?

Suspense and lazy components work hand-in-hand to make code splitting simple and seamless in React.

  • React provides React.lazy() to dynamically import a component only when it is needed.
  • React.lazy() returns a special version of the component that can tell React it is not ready yet.
  • When React hits a lazy component that isn’t ready, it looks for the nearest <Suspense> boundary and shows the fallback instead of crashing.

Here's the flow:

  1. You use React.lazy(() => import('./MyComponent')) to dynamically load a component.
  2. The component isn’t immediately available.
  3. React suspends rendering at that point.
  4. The <Suspense fallback={...}> UI is displayed.
  5. Once the component is loaded, React resumes rendering with the loaded component.

Example:

import { lazy, Suspense } from 'react'; const MyLazyComponent = lazy(() => import('./MyLazyComponent')); function App() { return ( <Suspense fallback={<h1>Loading component...</h1>}> <MyLazyComponent /> </Suspense> ); }

Key Takeaways:

  • lazy is for dynamic imports.
  • Suspense is for handling the waiting.
  • Together, they improve performance and user experience by loading only what's needed when it's needed.