React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 22

How do you implement lazy loading in a React application?

Answer:

Lazy loading in a React application refers to the technique of loading components or resources only when they are needed, which can improve the performance and user experience of your application by reducing the initial load time. React provides built-in support for lazy loading components through React.lazy and Suspense.

Step-by-Step Guide to Implement Lazy Loading in React

  1. Using React.lazy for Component Lazy Loading:

    • React.lazy allows you to define a component that will be loaded dynamically when it is rendered for the first time.
  2. Using Suspense for Fallback UI:

    • React.Suspense provides a fallback UI (like a loading spinner) while the lazy component is being loaded.

Example: Lazy Loading a Component

Step 1: Define the Lazy Loaded Component

Assume you have a component HeavyComponent.js that you want to load lazily.

HeavyComponent.js

import React from 'react';

function HeavyComponent() {
  return (
    <div>
      <h1>This is a heavy component!</h1>
      <p>It takes some time to load.</p>
    </div>
  );
}

export default HeavyComponent;

Step 2: Import the Component Lazily

Use React.lazy to import the component lazily in the parent component.

App.js

import React, { Suspense, lazy } from 'react';

// Lazy load the component
const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <div>
      <h1>Welcome to My App</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <HeavyComponent />
      </Suspense>
    </div>
  );
}

export default App;

Explanation

  1. Lazy Load with React.lazy:

    • const HeavyComponent = lazy(() => import('./HeavyComponent')); dynamically imports the HeavyComponent only when it is needed.
  2. Provide Fallback UI with Suspense:

    • Suspense is used to wrap the lazy-loaded component and provides a fallback prop to display a loading indicator while the component is being loaded.
    • <Suspense fallback={<div>Loading...</div>}> ensures that a loading message is displayed until HeavyComponent is fully loaded.

Example: Lazy Loading Routes with React Router

React Router also supports lazy loading of routes using React.lazy and Suspense.

App.js

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

// Lazy load the components
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
const Contact = lazy(() => import('./Contact'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;

Explanation

  1. Lazy Load Routes:

    • Each route component (Home, About, Contact) is lazily loaded using React.lazy.
  2. Provide Fallback UI with Suspense:

    • Suspense wraps the Switch component, ensuring that the fallback UI is shown while any of the route components are being loaded.

Additional Techniques for Lazy Loading

  1. Code Splitting:

    • Code splitting can be achieved with tools like Webpack. It allows you to split your code into various bundles that can be loaded on demand.
    • React.lazy and dynamic imports enable code splitting by breaking your application into smaller chunks that are loaded as needed.
  2. React Loadable:

    • Although React.lazy is now the preferred method, react-loadable was a popular library for handling lazy loading before React 16.6. It provides more features and customization options.

Example with react-loadable:

import Loadable from 'react-loadable';

const HeavyComponent = Loadable({
  loader: () => import('./HeavyComponent'),
  loading: () => <div>Loading...</div>,
});

function App() {
  return (
    <div>
      <h1>Welcome to My App</h1>
      <HeavyComponent />
    </div>
  );
}

export default App;

Conclusion

Lazy loading in React helps improve the performance and user experience by loading components or resources only when needed. The built-in support through React.lazy and Suspense makes it straightforward to implement lazy loading in your React applications. This technique is especially useful for large components, routes, and other resources that can be split into smaller chunks and loaded on demand.

Recent job openings