What are the consequences of mutating state in a reducer?

Mutating state is an anti-pattern in React. React uses a rendering engine which depends on the fact that state changes are observable. This observation is made by comparing previous state with next state. It will alter a virtual dom with the differences and write changed elements back to the dom.

When you alter the internal state, React does not know what’s changed, and even worse; it’s notion of the current state is incorrect. So the dom and virtual dom will become out of sync.

Redux uses the same idea to update it’s store; an action can be observed by reducers which calculate the next state of the store. Changes are emitted and for example consumed by react-redux connect.

So in short: never ever, mutate state. Instead of Object.assign you can use the stage-3 spread syntax:

{...previousState,...changes}

Also please note, this is true for arrays as well!

Leave a Comment