Both are used to prevent unnecessary re-renders by doing a shallow comparison of props, but they are meant for different component types.
πΉ React.PureComponent
- Used with class components
- Automatically implements
shouldComponentUpdate - Performs shallow comparison of
propsandstate
Example
class MyComponent extends React.PureComponent {
render() {
return <div>{this.props.count}</div>;
}
}
Key points
β Class-based
β Compares props + state
β Cannot customize comparison easily
πΉ React.memo
- Used with functional components
- Prevents re-render if props don’t change
- Can accept a custom comparison function
Example
const MyComponent = React.memo(({ count }) => {
return <div>{count}</div>;
});
With custom comparison
React.memo(Component, (prevProps, nextProps) => {
return prevProps.count === nextProps.count;
});
Key points
β Function-based
β Compares props only
β Custom comparison supported
π₯ Key Differences
| Feature | React.memo | PureComponent |
|---|---|---|
| Component type | Functional | Class |
| Comparison | Props only | Props + State |
| Custom compare | β Yes | β No |
| Introduced in | React 16.6 | Earlier React |
| Hooks support | β Yes | β No |
β οΈ Common Pitfall (Both)
- Shallow comparison fails for mutated objects
props.user.name = "New"; // β mutation
Always use immutable updates.
π― Short Interview Answer
React.memois used with functional components to memoize renders based on props, whilePureComponentis used with class components and performs shallow comparison on both props and state.React.memoalso allows custom comparison logic.
β One-line summary
PureComponent is for classes; React.memo is for functions—with more flexibility.