Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it considered ok to mutate a shallow copy of my state?

Consider the following:

    [SELECT]: (state, action) => {
      let newState = {...state, newState} 
      delete newState[action.payload.key]
      return(newState)
}

Why is it acceptable for me to mutate the shallow copy, return it and still satisfy the rule about not mutating my state?

like image 943
S. Schenk Avatar asked Mar 12 '23 08:03

S. Schenk


2 Answers

It is acceptable because (at least in your example code), the mutation is on the shallow object, so you are not modifying an object that any other code is currently referring to.

It would not be acceptable to make a shallow copy and then modify a nested object! The key is that you clone any and all objects in the object tree that are on the path to the deep property you wish to change.

From the Redux FAQ:

It’s important to remember that whenever you update a nested value, you must also return new copies of anything above it in your state tree. If you have state.a.b.c.d, and you want to make an update to d, you would also need to return new copies of c, b, a, and state. This state tree mutation diagram demonstrates how a change deep in a tree requires changes all the way up.

like image 188
Brandon Avatar answered Mar 16 '23 03:03

Brandon


A reducer in Redux should be pure, which means it must guarantee that it doesn't change or effect anything outside of it's own function (i.e. produces no side effects). If you mutate the passed state object directly, you violate this.

By creating a new copy, you know for certain that no other part of your application uses it (it was just created, so how could they?). Which in turn means that it's safe to mutate it without worrying about strange side effects.

like image 32
tobiasandersen Avatar answered Mar 16 '23 04:03

tobiasandersen