Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
import React, { PureComponent } from 'react';
class MyComponent extends PureComponent {
render() {
console.log('Render!');
return <div>{this.props.name}</div>;
}
}
Inside PureComponent this method is already implemented:
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this.props, nextProps) || shallowCompare(this.state, nextState);
}
| Component | Behavior |
|---|---|
React.Component | Always re-renders when props or state change |
React.PureComponent | Compares props and state, and can avoid unnecessary render |
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.
PureComponent doesn't work with nested objects or arrays (if you mutated them)spread, map, filter, slice) for correct comparisonLimitation:
PureComponent does only shallow comparison. If you change object internals without changing reference — React won't notice.
props and state without side effectsReact.memo)const MyComponent = React.memo((props) => {
return <div>{props.value}</div>;
});
PureComponent helps avoid unnecessary re-renders in class componentsprops and state by reference