Hacker News new | ask | show | jobs
by acemarke 2144 days ago
Thanks!

Quick summary:

Immer is an incredibly useful immutable update library, created by Michel Weststrate (author of MobX).

It exports a single function `produce(originalState, updateCallback)`. The callback receives a `draftState` value that _looks_ like your original state, but has been wrapped in an ES6 Proxy. You can then "mutate" the draft all you want. Internally, Immer tracks all the mutations, and the final result is a safely immutably-updated value.

It drastically simplifies immutable update logic - no more nested spread operators!

See https://immerjs.github.io/immer/docs/introduction and https://redux.js.org/recipes/structuring-reducers/immutable-... .

Redux Toolkit comes with Immer built into our `createReducer` and `createSlice` APIs automatically.

1 comments

When I first came across Immer, I wasn’t impressed. I though “If you’re going to the trouble of using functional-ish state management, why add a “mutations-like” API in there. Surely you’re “crossing the streams?”

But then a couple of weeks later I had to wrangle data in subsections of three “slices“ of state at the same time.

Immer lets you focus on just the state you want to change, and hides the problem of maintaining the state you don’t want to change. Brilliant. I’ll take the “it looks like mutation” hit for that.

Yeah, Dan's pointed out a number of times that even with FP and immutability, _local_ mutation is fine. After all, the mechanism for immutable updates is to make copies of the original data, and then mutate / overwrite pieces of the copies.

Immer just does that in a really slick way.

My only concern for using Immer by default in RTK is the potential that someone would learn Redux by osmosis through looking at a codebase where every reducer is doing `state.someField = someValue`, think that actual mutation _is_ the right way to use Redux, and then try to do the same thing in another project and actually mutate data for real.

I can't prevent that, so my only answer was to repeatedly emphasize in this new tutorial that you _must_ do immutable updates, and that you can _only_ "mutate" inside of RTK's APIs thanks to Immer:

- https://redux.js.org/tutorials/essentials/part-2-app-structu...

- https://redux.js.org/tutorials/essentials/part-3-data-flow#s...

But yeah, the massive improvements in code size and readability are more than sufficient to justify the small potential downside there.