What does it mean for a React component to be pure?
A pure component returns the same JSX for the same props, state and context, and changes nothing outside itself while rendering. Purity lets React re-run, skip or repeat renders safely, including in Strict Mode.
Explain it simply
A pure component is like a calculator: put in 2 + 2 and you always get 4, and pressing the keys does not change the room. Rendering should work the same way. It reads inputs and returns JSX, nothing more.
Side effects such as changing a global variable, mutating props, or writing to the DOM during render break this promise. React may render a component more than once (Strict Mode does it twice in development), so an impure render gives different results each time.
Example
let count = 0;
function Bad() {
count++; // changes something outside: impure
return <p>Seen {count}</p>;
}
function Good({ n }) {
return <p>Seen {n}</p>; // same n, same output
}Side effects belong in event handlers or in useEffect, not in the render body.
What to say in the interview
"A pure component gives the same output for the same props, state and context and does not mutate anything outside its own scope during render. React depends on that so it can pause, repeat or skip renders. Strict Mode double-rendering in development helps catch impure code. Side effects go in handlers or effects."
Common mistakes
- Mutating a prop or a module-level variable during render.
- Creating random IDs in the render body.