Contents of React Interview Questions

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

What is Suspense and how does it help with lazy loading?

Suspense is a React component that lets you handle the loading state when components are being lazily loaded. It acts as a placeholder until the lazy-loaded component is ready.

Why Suspense?
When you lazy load components (using React.lazy), fetching the component might take time. Suspense lets you show a fallback UI (like a loader or a message) during that waiting time.

Basic Usage Example:

import React, { Suspense } from 'react'; const Profile = React.lazy(() => import('./Profile')); function App() { return ( <div> <Suspense fallback={<div>Loading profile...</div>}> <Profile /> </Suspense> </div> ); }

In this example:

  • <div>Loading profile...</div> is shown until the Profile component is fully loaded.
  • Once Profile finishes loading, React replaces the fallback with the actual component.

Key Point: Suspense smoothens the user experience during lazy loading by providing a graceful loading indicator.


Real-world Example:

Imagine a social media app where the user's feed loads immediately, but the "Friend Suggestions" panel is a separate component that's not critical for the initial view.
Using Suspense + React.lazy, you can lazy load that panel — showing a nice spinner while it loads — without blocking the main content!