Is the state returned from the useReducer Hook a "deep copy" or a reference of a reducers output?

Viewed 1383

I'm currently implementing global state handling in React using the Context API in combination with the useReducer hook.

I have two concerns regarding mutability:

  • When updating state in my reducers, do I need to e.g use Lodash's cloneDeep function to sever the reference between the objects going into my reducer and the stored state?
  • Is it possible to ruin the global state by manually mutating it outside reducers, or will it behave like "normal React state" in the sense that manual mutations will get overwritten during the next update cycle?

For reference: docs

2 Answers

Both useState and useReducer give you the exact value reference that you saved (either by calling someSetter(newValue), or returning a value from the reducer function).

In either case, manually mutating the value is wrong. In particular, both of them will bail out of updates if you return the identical reference as last time, so you should always update values immutably.

Related