Contents of React Interview Questions

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

How to use shouldComponentUpdate for performance optimization?

shouldComponentUpdate is a lifecycle method in class-based React components that lets you control whether a component should re-render or not.

How it works:

  • When a component’s state or props change, shouldComponentUpdate(nextProps, nextState) is called.
  • By default, it returns true (always re-render).
  • You can override it to return false if the new props or state do not affect the output, preventing unnecessary re-render.

Example:

class MyComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { return nextProps.value !== this.props.value; } render() { console.log('Rendering...'); return <div>{this.props.value}</div>; } }

In this case, the component will only re-render if the value prop actually changes.

Tips:

  • Be careful with complex props like objects and arrays — they may need deep comparison.
  • For simple components, you can extend React.PureComponent instead of manually writing shouldComponentUpdate. PureComponent does shallow comparison automatically.

PureComponent Example:

class MyComponent extends React.PureComponent { render() { return <div>{this.props.value}</div>; } }

Summary:
Use shouldComponentUpdate (or PureComponent) to manually control re-renders and boost performance in class components. In functional components, you can achieve similar results using React.memo.