React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 31

Explain the concept of React.memo and its use case.

Answer:

React.memo is a higher-order component (HOC) in React that provides a way to optimize functional components by memoizing them. When a component is wrapped in React.memo, React will memoize the rendered output and only re-render the component if its props have changed. This can help to prevent unnecessary re-renders and improve performance.

Syntax

const MemoizedComponent = React.memo(Component);

How React.memo Works

  • React.memo performs a shallow comparison of the component’s props.
  • If the props are the same between renders, React skips rendering the component and reuses the last rendered result.
  • If the props have changed, React re-renders the component.

Use Case for React.memo

  1. Pure Functional Components:

    • React.memo is ideal for functional components that render the same output given the same props.
    • It is especially useful when the component performs heavy computations or renders large lists.
  2. Avoiding Re-renders:

    • When a parent component re-renders, all of its children also re-render by default. Using React.memo on child components can prevent them from re-rendering if their props haven’t changed.
  3. Performance Optimization:

    • Useful in optimizing components that are expensive to render due to complex UI or intensive data processing.

Example: Using React.memo

Let's consider a scenario where we have a component that renders a list of items, and we want to prevent unnecessary re-renders.

Without React.memo

import React, { useState } from 'react';

function ListItem({ item }) {
  console.log('Rendering:', item);
  return <li>{item}</li>;
}

function List({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <ListItem key={index} item={item} />
      ))}
    </ul>
  );
}

function App() {
  const [count, setCount] = useState(0);
  const items = ['Apple', 'Banana', 'Cherry'];

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment: {count}</button>
      <List items={items} />
    </div>
  );
}

export default App;

In this example, clicking the button re-renders the entire App component, causing all ListItem components to re-render, even though their props haven’t changed.

With React.memo

import React, { useState } from 'react';

const ListItem = React.memo(({ item }) => {
  console.log('Rendering:', item);
  return <li>{item}</li>;
});

function List({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <ListItem key={index} item={item} />
      ))}
    </ul>
  );
}

function App() {
  const [count, setCount] = useState(0);
  const items = ['Apple', 'Banana', 'Cherry'];

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Increment: {count}</button>
      <List items={items} />
    </div>
  );
}

export default App;

Explanation

  1. Memoization:

    • ListItem is wrapped with React.memo, which memoizes the component.
    • The ListItem components will only re-render if their item prop changes.
  2. Avoiding Unnecessary Re-renders:

    • When the button is clicked, the App component re-renders, but ListItem components do not re-render because their props have not changed.
    • This optimization reduces the number of renders and can improve performance, especially with large lists or complex UI components.

Custom Comparison Function

By default, React.memo uses a shallow comparison of props. If you need a custom comparison logic, you can pass a second argument to React.memo, which is a comparison function.

Example with Custom Comparison Function

const ListItem = React.memo(
  ({ item }) => {
    console.log('Rendering:', item);
    return <li>{item}</li>;
  },
  (prevProps, nextProps) => {
    return prevProps.item === nextProps.item;
  }
);

In this example, prevProps and nextProps are compared using a custom logic to determine if the component should re-render.

Conclusion

React.memo is a powerful optimization tool for functional components in React. It helps prevent unnecessary re-renders by memoizing the component output and only re-rendering when props change. This can lead to significant performance improvements, especially in components that are expensive to render or in large applications where many components are rendered frequently. By understanding and applying React.memo, you can optimize your React applications and ensure they run more efficiently.

Recent job openings