- A Pure Component is a component that renders the same output if its props and state haven’t changed.
- It implements a shallow comparison of
propsandstateto decide whether to re-render. - Helps in avoiding unnecessary re-renders and boosts performance.
🔹 In Class Components (using React.PureComponent)
import React, { PureComponent } from "react";
class MyComponent extends PureComponent {
render() {
console.log("Rendering...");
return <h2>Hello, {this.props.name}</h2>;
}
}
export default function App() {
return (
<div>
<MyComponent name="Dev" />
<MyComponent name="Dev" /> {/* ❌ Will NOT re-render since props are same */}
</div>
);
}
👉 Unlike React.Component, React.PureComponent prevents unnecessary re-rendering when props/state are unchanged.
🔹 In Functional Components (using React.memo)
Functional components don’t have PureComponent, so we use React.memo instead.
import React, { useState } from "react";
const Child = React.memo(({ name }) => {
console.log("Child rendered!");
return <h2>Hello, {name}</h2>;
});
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<Child name="Dev" />
<button onClick={() => setCount(count + 1)}>Increment {count}</button>
</div>
);
}
👉 Here, clicking the button re-renders the parent, but Child won’t re-render since name is the same.
🔹 Shallow Comparison in Pure Components
- Primitive values (string, number, boolean) → compared by value.
- Objects/arrays/functions → compared by reference.
⚠️ Example:
<Child user={{name: "Dev"}} />
Even if name is same, a new object reference is created each render → Child will re-render.
🔹 Advantages
✅ Prevents unnecessary re-renders.
✅ Improves performance in large apps.
🔹 Disadvantages
❌ Only does shallow comparison, so may not work well with nested objects.
❌ If not used carefully, can cause confusion or even worse performance.
✅ Short Interview Answer
“A Pure Component is a component that re-renders only when its props or state change. In class components, we use
React.PureComponent, and in functional components, we useReact.memo. It uses shallow comparison to avoid unnecessary renders and improve performance.”