React Concept: Purity
By Flavio
Published · Updated
Tagged: React
Understand purity in React: a pure function returns the same output for the same input with no side effects, and a pure component depends only on its props.
In JavaScript, when a function does not mutate objects but just returns a new object, it’s called a pure function.
A function, or a method, in order to be called pure should not cause side effects and should return the same output when called multiple times with the same input.
A pure function takes an input and returns an output without changing the input nor anything else.
Its output is only determined by the arguments. You could call this function 1M times, and given the same set of arguments, the output will always be the same.
React applies this concept to components. A React component is a pure component when its output is only dependent on its props.
React expects every component to be pure while it renders: same props, state and context in, same JSX out, with no side effects during rendering. Side effects go in event handlers or in useEffect.
A function component that only reads its props is pure:
const Button = props => {
return <button>{props.message}</button>
}
Class components can be pure if their output only depends on the props:
class Button extends React.Component {
render() {
return <button>{this.props.message}</button>
}
}
What makes a component impure
The most common mistake is changing a variable that lives outside the component while rendering:
let guest = 0
function Cup() {
guest = guest + 1 // 🚩 changes a variable that existed before
return <h2>Tea cup for guest #{guest}</h2>
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
)
}
Every time React renders Cup, the output is different, even with the same props. If React renders it again for any reason, the numbers change.
The fix is to pass the value in as a prop:
function Cup({ guest }) {
return <h2>Tea cup for guest #{guest}</h2>
}
export default function TeaSet() {
return (
<>
<Cup guest={1} />
<Cup guest={2} />
<Cup guest={3} />
</>
)
}
Other things that make rendering impure:
- changing a prop or a state object directly, like
props.items.push(x) - calling
Math.random()ornew Date()while rendering and showing the result, because every render gives a different output - starting a
fetch(), setting a timer or writing tolocalStoragein the component body - changing the DOM by hand, like
document.title = ..., in the component body
Changing local variables is fine
Purity is about things that existed before the component was called. You can create an array during render and push into it as much as you want, because no other code can see it:
export default function TeaGathering() {
const cups = []
for (let i = 1; i <= 12; i++) {
cups.push(<Cup key={i} guest={i} />)
}
return cups
}
Strict Mode finds impure components for you
In development, when your app is wrapped in <StrictMode>, React calls each component function twice. A pure component gives the same result both times, so you don’t notice anything.
The impure Cup above shows guest #2, #4 and #6 instead of #1, #2 and #3. That’s the hint something is wrong. In production React calls it once. See React StrictMode for how to turn it on.
Where side effects go
Your app still needs to do things: save data, call APIs, start animations. You do them outside of rendering.
- In event handlers, like
onClickoronSubmit. They run when the user does something, not during render, so they don’t need to be pure. This is the first place to look. - In
useEffect, when there’s no event to attach it to, for example to connect to a server when a component appears on screen. React runs it after rendering.
Why React cares
React relies on purity to do its job:
- Server rendering: the same inputs give the same HTML, so a component can render on the server for many requests.
- Skipping work: if a component’s props didn’t change, React can reuse the previous result, for example with
memo. - Stopping a render halfway: React can start rendering, throw the work away when newer data arrives, and start again. That’s only safe when rendering has no side effects.
Don’t confuse pure components with React.PureComponent. That’s a class you can extend so a class component skips re-rendering when its props and state are shallowly equal to the previous ones. Every component should be pure, whether or not it uses PureComponent or memo.
Want me to talk about your product? You can sponsor this site.