4 ms·
Deep cloning is almost never the right answer - you'll end up copying _too many_ object references, which is extra work, and that can also lead to unnecessary r
by acemarke 4y ago
Deep cloning is almost never the right answer - you'll end up copying _too many_ object references, which is extra work, and that can also lead to unnecessary re-renders depending on what your components are trying to do.
A correct immutable update is more like a "nested shallow update", copying all levels of nested keypaths leading to the actual value you want to update.
If you prefer to avoid writing those immutable operations by hand, Immer is a fantastic tool for simplifying the code by using "mutating" syntax that gets turned into a safe and correct immutable update:
- https://immerjs.github.io/immer/ https://immerjs.github.io/immer/
- https://beta.reactjs.org/learn/updating-objects-in-state#write-concise-update-logic-with-immer https://beta.reactjs.org/learn/updating-objects-in-state#wri...
We even use Immer by default in Redux Toolkit:
- https://redux-toolkit.js.org/usage/immer-reducers https://redux-toolkit.js.org/usage/immer-reducers
- petilon 4y agoimmer makes an "efficient copy" of the object, right? Keeping references to some nested objects in the original object when possible? If so that's cool... but not sure it is worth the effort.
- acemarke 4y agoImmer does a correct nested immutable update, same as if you wrote the corresponding nested spread operations by hand. It _only_ updates the nesting paths that led to the value that got modified. So yes, if you have a nested object with a bunch of different fields, and you update `state.a.b.c = 123`, it makes copies of `b`, `a`, and `state`, but preserves all other nested references that are anywhere inside of `state`. It's the same as if you wrote: return { ...state, a: { ...state.a, b: { ...state.a.b, c: 123 } } } but obviously much shorter and easier to read / maintain :) It also conveniently eliminates the chance of a _real_ accidental mutation (which in the case of Redux was always the #1 cause of bugs in Redux apps).
- petilon 4y agoThat's awesome! It lets me use POJO (Plain Old JavaScript Objects), and it makes efficient copies? Definitely going to give this a try.
- deleted 4y ago[deleted]