A pure component in React is a component that renders only when its props or state change. A Pure Component uses shallow comparison in the shouldComponentUpdate
method to determine if re-rendering is necessary.
Creating a pure component:
- Using the
React.PureComponent
class:
class MyComponent extends React.PureComponent { render() { return <div>{this.props.value}</div>; } }
- Using functional components with
React.memo
:
const MyComponent = React.memo(function MyComponent(props) { return <div>{props.value}</div>; });
Benefits of a pure component:
- Performance optimization: Pure Component prevents unnecessary renders, which can enhance application performance.
- Simpler code: Using Pure Component simplifies code by eliminating the need for manually implementing
shouldComponentUpdate
. - Deterministic rendering: Since Pure Component only renders when its props or state change, the rendering behavior becomes more predictable.
Pure components are useful for improving the performance of React applications by minimizing the number of renders.