Community JavaScript Snippet

How I Stopped Mutating Nested State in React

The bug we shipped: a deeply nested form state was being updated in place, and React refused to re-render. Here is the 25-line `setIn` helper I now reach for instead of Immer.

How I Stopped Mutating Nested State in React

The bug we shipped: a deeply nested form state was being updated in place, and React refused to re-render. Here is the 25-line `setIn` helper I now reach for instead of Immer.

JavaScript
Frontend
3 snippets
react
hooks
immutability
kwamehenderson

By @kwamehenderson

February 23, 2026

·

Updated May 18, 2026

1,120 views

17

4.4 (14)

The bug is that setState(prev) calls Object.is(prev, next) to decide whether to re-render. If we mutated state.user.profile.address.city in place, every level of that tree still points to the same object, so React bails out and the screen stays stale. The fix is uglier than it needs to be: spread the root, the user, the profile, AND the address, only then assign the new city. Notice the reference-identity diffs at the bottom: only the path I touched gets new references, every other subtree is shared. That preserves the React.memo short-circuit for siblings, which is the reason we bother with immutability in the first place.