5 ms·
When updating deeply-nested immutable objects, the Immer library is great. You call the `produce(immutableValue, draft => { ... })` function with some immutable
by AgentME 4y ago
When updating deeply-nested immutable objects, the Immer library is great. You call the `produce(immutableValue, draft => { ... })` function with some immutable value and a callback function that manipulates a mutable proxy object mimicking the immutable value, and then the function returns a new immutable value with the same changes made by the callback function. The mutable proxy object never escapes the callback, so the use of Immer stays self-contained as an implementation detail of your code without infecting your component's public API or anything.
Another alternative is the "immutability-helper" library, which was originally published by the React team as "react-addons-update". It's a lighter library with less proxy magic going on, but at the cost of being more explicit: instead you create an object describing how to update an immutable value to produce a new immutable value. I've used it in the past in a few places but mostly recommend Immer over it now.
- acemarke 4y agoYeah, we specifically built Redux Toolkit around Immer from the very first prototype that I wrote. I had catalogued _dozens_ of immutable update libs between 2015-2018, and Immer is simply superior to all of them. Which is why Immer is a non-negotiable part of RTK, and something we specifically tell everyone they should be using with Redux: - https://redux.js.org/style-guide/#use-immer-for-writing-immutable-updates https://redux.js.org/style-guide/#use-immer-for-writing-immu... - https://redux-toolkit.js.org/usage/immer-reducers https://redux-toolkit.js.org/usage/immer-reducers (in fact, I recently got quoted on the top of the Immer docs with a tweet I wrote saying how awesome Immer is :) https://immerjs.github.io/immer/ https://immerjs.github.io/immer/ )
- TurningCanadian 4y agoWhere will the Record & Tuple proposal (Stage: 2) fit in? https://tc39.es/proposal-record-tuple/tutorial/ https://tc39.es/proposal-record-tuple/tutorial/
- acemarke 4y agoI'm not sure, tbh. I agree that having the ability to construct objects/arrays that are compared by nested values, rather than references, will be useful. But, given that Immer already exists, and only meaningfully requires ES6 Proxy support, I'm not sure how much of an impact the availability of Records will have. In the case of RTK specifically... Immer is built into `createSlice/createReducer`, and it's _always_ getting called even if you manually create an immutably-updated result yourself. So I don't see any real change or benefit there.
- rhacker 4y agoWe're using something called Recoil - I'm still getting used to it, but I think it has some similarities.
- 8n4vidtmkvmk 4y agoi dont like proxy magic, its bitten me before. immutability helper ftw