Course contentsShow
← React
Lesson 300 of 2,3969. Class Components (Legacy Overview)Free lesson

shouldComponentUpdate: Manual Render Optimization

Returning false to prevent re-renders based on shallow comparison of props and state.

shouldComponentUpdate: Manual Render Optimization

What you'll learn: How to manually control when a class component re-renders by comparing props and state.

By default, React re-renders a component whenever this.setState() is called or new props arrive. But sometimes those changes don't actually affect what's displayed—you might update an unrelated state property, or receive the same prop values again. Re-rendering when nothing visible changes wastes performance.

The Optimization Hook

shouldComponentUpdate is a lifecycle method that lets you intercept the re-render decision. It receives nextProps and nextState as arguments, and you return either true (proceed with render) or false (skip it).

class UserCard extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    // Only re-render if the name actually changed
    if (nextProps.name !== this.props.name) {
      return true;
    }
    return false;
  }

  render() {
    return <div>{this.props.name}</div>;
  }
}

Shallow Comparison Pattern

The most common pattern is shallow comparison: check if any props or state values changed using strict equality (!==). If nothing changed at the top level, return false to prevent the render.

shouldComponentUpdate(nextProps, nextState) {
  return (
    this.props.userId !== nextProps.userId ||
    this.state.isExpanded !== nextState.isExpanded
  );
}

Think of this like a bouncer at a club checking IDs: "Has anything actually changed? No? Then you don't need to go through the expensive render process."

When to Use This

This method is purely a performance optimization. Only add it when profiling shows unnecessary re-renders slowing your app. Incorrect logic here can cause bugs where updates are ignored.

Key Takeaway: shouldComponentUpdate lets you return false to prevent re-renders when shallow comparison shows props and state haven't meaningfully changed—manual performance optimization for class components.