Have you heard about Hack Frontend Community?Join us on Telegram!
Practice React Problems

React.PureComponent: Shallow Comparison for Performance

PureComponent is a special type of class component in React that automatically implements shouldComponentUpdate() method with shallow comparison of props and state.

If input data (props or state) haven't changed, component doesn't re-render.


Syntax

import React, { PureComponent } from 'react';

class MyComponent extends PureComponent {
  render() {
    console.log('Render!');
    return <div>{this.props.name}</div>;
  }
}

How Does It Work?

Inside PureComponent this method is already implemented:

shouldComponentUpdate(nextProps, nextState) {
  return shallowCompare(this.props, nextProps) || shallowCompare(this.state, nextState);
}
  • Comparison is shallow (shallow compare)
  • This means if you pass new object/array, even with same data — component will re-render
  • But if references haven't changed — there won't be re-render

What's the Difference from Component?

ComponentBehavior
React.ComponentAlways re-renders when props or state change
React.PureComponentCompares props and state, and can avoid unnecessary render

Example: when it works

class Counter extends React.PureComponent {
  render() {
    console.log("Render Counter");
    return <div>{this.props.value}</div>;
  }
}

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <Counter value={count} />
      <button onClick={() => setCount(0)}>Update</button>
    </>
  );
}

If you click button, count value won't change — and PureComponent won't re-render.

Important to Remember

  • PureComponent doesn't work with nested objects or arrays (if you mutated them)
  • Always use immutability (spread, map, filter, slice) for correct comparison

Limitation:

PureComponent does only shallow comparison. If you change object internals without changing reference — React won't notice.

When to Use?

  • If component depends only on props and state without side effects
  • When component often re-renders with same data
  • When working with class components (in functional use React.memo)

Alternative for Functional Components

const MyComponent = React.memo((props) => {
  return <div>{props.value}</div>;
});

Conclusion

  • PureComponent helps avoid unnecessary re-renders in class components
  • Compares props and state by reference
  • Ideal for simple or reusable components without deep objects
Practice React Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.