You're unable to read via this Friend Link since it's expired. Learn more
Member-only story
The Ugliest Pattern In React

Brace yourselves. Out of all the nastiness in the React world, nothing comes close to this.
Usually, you will update state in event handlers. However, in rare cases, you might want to adjust state in response to rendering — for example, you might want to change a state variable when a prop changes.
Granted. In most cases, you don’t need this:
- If the value you need can be computed entirely from the current props or other state, then you can remove the redundant state altogether.
- If you want to reset the entire component tree’s state, pass a different key to your component.
- If you can, update all the relevant state in event handlers.
But let’s say that none of those conditions apply, and you still need to update a state when a prop changes.
To solve this problem, seasoned React devs know what to do: Update the state in an Effect.
Nope! The new docs explicitly tell you that an Effect is no good for this because it will cause the child tree to render twice. And sure, you want to avoid extra renders, but at what price?
The new docs recommend instead what I can only call The Ugliest Pattern In React™️. If you are brave to see it for yourself, here it is:
function CountLabel({ count }) {
const [prevCount, setPrevCount] = useState(count);
const [trend, setTrend] = useState(null);
if (prevCount !== count) {
setPrevCount(count);
setTrend(count > prevCount ? 'increasing' : 'decreasing');
}
return (
<>
<h1>{count}</h1>
{trend && <p>The count is {trend}</p>}
</>
);
}
The horror! Yes, it sets state in the render function! It breaks what’s arguably the most important rule of React: The render function must be pure.
I’ll let the docs excuse themselves and give you the full gory details:
You can only update the state of the currently rendering component like this. Calling the
set
function of another component during rendering is an error. This special case doesn’t mean you can break other rules of pure functions. […]
This pattern can be hard to understand and is usually best avoided. […]The rest of your component…