What are Pure Components in React?
In React, Pure Components are a special type of component that optimize rendering performance. A Pure Component automatically implements a shallow comparison (shallow comparison
) on its props and state to decide whether it needs to re-render.
This means if the previous props and the next props are the same (no changes in shallow comparison), React skips re-rendering the component, improving performance.
Pure Components are mainly used for functional optimization in large applications where frequent re-renders can cause performance issues.
How to create a Pure Component:
- In class components, you can extend
React.PureComponent
instead ofReact.Component
.
import React, { PureComponent } from 'react'; class MyComponent extends PureComponent { render() { return <div>{this.props.name}</div>; } }
- In functional components, you can use
React.memo()
, which behaves similarly for function-based components.
import React from 'react'; const MyComponent = React.memo(function MyComponent(props) { return <div>{props.name}</div>; });
Key Points:
- Performs a shallow comparison of props and state.
- Prevents unnecessary re-renders, improving performance.
- Ideal when props and state are simple and not deeply nested.
- If your props/state are complex (deep structures like nested objects), shallow comparison might not be enough — you might still need manual optimizations.