What is Pure Component in React: Explanation and Example
PureComponent in React is a component that automatically implements a shallow comparison of props and state to decide if it should re-render. It helps improve performance by preventing unnecessary updates when data has not changed.How It Works
A PureComponent in React works like a smart friend who only pays attention when something important changes. Instead of re-rendering every time its parent updates, it checks if its input data (props and state) has actually changed by comparing the old and new values shallowly.
This shallow comparison means it looks at the first level of properties to see if they are different. If nothing changed, it skips re-rendering, saving time and resources. Think of it like checking if your keys are in the same pocket before searching again.
This behavior is automatic in PureComponent, so you don't have to write extra code to optimize rendering. It is especially useful when components receive simple data and you want to avoid slow updates.
Example
This example shows a PureComponent that only re-renders when its prop count changes. The button increments a separate state that does not affect the pure component, so it won't re-render unnecessarily.
import React, { PureComponent, useState } from 'react'; class Counter extends PureComponent { render() { console.log('Counter render'); return <h2>Count: {this.props.count}</h2>; } } export default function App() { const [count, setCount] = useState(0); const [other, setOther] = useState(0); return ( <div> <Counter count={count} /> <button onClick={() => setCount(count + 1)}>Increment Count</button> <button onClick={() => setOther(other + 1)}>Increment Other</button> <p>Other state: {other}</p> </div> ); }
When to Use
Use PureComponent when your component renders the same output given the same props and state, and you want to avoid unnecessary re-renders for better performance.
It is ideal for components with simple, immutable data where shallow comparison is enough to detect changes. For example, list items, buttons, or display components that receive primitive values or simple objects.
Avoid using PureComponent if your props or state are complex nested objects that change deeply, as shallow comparison might miss changes and cause bugs.
Key Points
- PureComponent automatically implements
shouldComponentUpdatewith shallow prop and state comparison. - It helps improve performance by skipping unnecessary renders.
- Best for components with simple, immutable props and state.
- Not suitable for deeply nested or mutable data structures.
- Use functional components with
React.memofor similar behavior in modern React.