Member-only story

The Ugliest Pattern In React

Sebastian Carlos
3 min readJan 7, 2023

--

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:

--

--

Sebastian Carlos
Sebastian Carlos

Responses (6)