Skip to content
Myr

docs: add opensource award

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 96f2b2e · Browse files · 1 file+211 added−211 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+211 added−211 removed

  • other:+211 added−211 removed

1 file+211 added−211 removed

modified:readme.md+211 added-211 removed
4 unmodified lines
5[![npm](https://img.shields.io/npm/v/immer.svg)](https://www.npmjs.com/package/immer) [![Build Status](https://travis-ci.org/immerjs/immer.svg?branch=master)](https://travis-ci.org/immerjs/immer) [![Coverage Status](https://coveralls.io/repos/github/immerjs/immer/badge.svg?branch=master)](https://coveralls.io/github/immerjs/immer?branch=master) [![Minzipped size](https://img.shields.io/bundlephobia/minzip/immer.svg)](https://bundlephobia.com/result?p=immer) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/michelweststrate)67_Create the next immutable state tree by simply modifying the current tree_89Winner of the "breakthrough of the year" [open source award](https://osawards.com/react/) in 20199Winner of the "Breakthrough of the year" [React open source award](https://osawards.com/react/) and "Most impactful contribution" [JavaScript open source award](https://osawards.com/javascript/) in 20191011### [Release notes](https://github.com/immerjs/immer/releases)1213Did Immer make a difference to your project? Consider buying me a coffee!<br/><a href="https://www.buymeacoffee.com/mweststrate" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>1415---1617- NPM: `npm install immer`18- Yarn: `yarn add immer`19- CDN: Exposed global is `immer`20 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`21 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`17- NPM: `npm install immer`18- Yarn: `yarn add immer`19- CDN: Exposed global is `immer`20 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`21 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`2223---2425- Egghead lesson covering all of immer (7m): [Simplify creating immutable data trees with Immer](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)26- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)25- Egghead lesson covering all of immer (7m): [Simplify creating immutable data trees with Immer](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)26- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)2728Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.2930The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it while keeping all the benefits of immutable data.
5 unmodified lines
36A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.3738## External resources3940- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)41- Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)42- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate45- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)40- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)41- Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)42- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate45- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)4647## API4849The Immer package exposes a default function that does all the work.
7 unmodified lines
57```javascript58import produce from "immer"5960const baseState = [61 {62 todo: "Learn typescript",63 done: true64 },65 {66 todo: "Try immer",67 done: false68 }61 {62 todo: "Learn typescript",63 done: true64 },65 {66 todo: "Try immer",67 done: false68 }69]7071const nextState = produce(baseState, draftState => {72 draftState.push({todo: "Tweet about it"})73 draftState[1].done = true72 draftState.push({todo: "Tweet about it"})73 draftState[1].done = true74})75```7677The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.
15 unmodified lines
93```9495## Benefits9697- Immutability with normal JavaScript objects and arrays. No new APIs to learn!98- Strongly typed, no string based paths selectors etc.99- Structural sharing out of the box100- Object freezing out of the box101- Deep updates are a breeze102- Boilerplate reduction. Less noise, more concise code.103- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)97- Immutability with normal JavaScript objects and arrays. No new APIs to learn!98- Strongly typed, no string based paths selectors etc.99- Structural sharing out of the box100- Object freezing out of the box101- Deep updates are a breeze102- Boilerplate reduction. Less noise, more concise code.103- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)104105Read further to see all these benefits explained.106107## Reducer Example
3 unmodified lines
111```javascript112// Redux reducer113// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114const byId = (state, action) => {115 switch (action.type) {116 case RECEIVE_PRODUCTS:117 return {118 ...state,119 ...action.products.reduce((obj, product) => {120 obj[product.id] = product121 return obj122 }, {})123 }124 default:125 return state126 }115 switch (action.type) {116 case RECEIVE_PRODUCTS:117 return {118 ...state,119 ...action.products.reduce((obj, product) => {120 obj[product.id] = product121 return obj122 }, {})123 }124 default:125 return state126 }127}128```129130After using Immer, that simply becomes:
1 unmodified line
132```javascript133import produce from "immer"134135const byId = (state, action) =>136 produce(state, draft => {137 switch (action.type) {138 case RECEIVE_PRODUCTS:139 action.products.forEach(product => {140 draft[product.id] = product141 })142 }143 })136 produce(state, draft => {137 switch (action.type) {138 case RECEIVE_PRODUCTS:139 action.products.forEach(product => {140 draft[product.id] = product141 })142 }143 })144```145146Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.147
9 unmodified lines
157/**158 * Classic React.setState with a deep merge159 */160onBirthDayClick1 = () => {161 this.setState(prevState => ({162 user: {163 ...prevState.user,164 age: prevState.user.age + 1165 }166 }))161 this.setState(prevState => ({162 user: {163 ...prevState.user,164 age: prevState.user.age + 1165 }166 }))167}168169/**170 * ...But, since setState accepts functions,171 * we can just create a curried producer and further simplify!172 */173onBirthDayClick2 = () => {174 this.setState(175 produce(draft => {176 draft.user.age += 1177 })178 )174 this.setState(175 produce(draft => {176 draft.user.age += 1177 })178 )179}180```181182## Currying
4 unmodified lines
187188```javascript189// mapper will be of signature (state, index) => state190const mapper = produce((draft, index) => {191 draft.index = index191 draft.index = index192})193194// example usage195console.dir([{}, {}, {}].map(mapper))
5 unmodified lines
201```javascript202import produce from "immer"203204const byId = produce((draft, action) => {205 switch (action.type) {206 case RECEIVE_PRODUCTS:207 action.products.forEach(product => {208 draft[product.id] = product209 })210 return211 }205 switch (action.type) {206 case RECEIVE_PRODUCTS:207 action.products.forEach(product => {208 draft[product.id] = product209 })210 return211 }212})213```214215Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).
3 unmodified lines
219```javascript220import produce from "immer"221222const byId = produce(223 (draft, action) => {224 switch (action.type) {225 case RECEIVE_PRODUCTS:226 action.products.forEach(product => {227 draft[product.id] = product228 })229 return230 }231 },232 {233 1: {id: 1, name: "product-1"}234 }223 (draft, action) => {224 switch (action.type) {225 case RECEIVE_PRODUCTS:226 action.products.forEach(product => {227 draft[product.id] = product228 })229 return230 }231 },232 {233 1: {id: 1, name: "product-1"}234 }235)236```237238##### Fun with currying
16 unmodified lines
255During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.256257Patches are useful in few scenarios:258259- To exchange incremental updates with other parties, for example over websockets260- For debugging / traces, to see precisely how state is changed over time261- As basis for undo/redo or as an approach to replay changes on a slightly different state tree259- To exchange incremental updates with other parties, for example over websockets260- For debugging / traces, to see precisely how state is changed over time261- As basis for undo/redo or as an approach to replay changes on a slightly different state tree262263To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:264265```javascript266import produce, {applyPatches} from "immer"267268let state = {269 name: "Micheal",270 age: 32269 name: "Micheal",270 age: 32271}272273// Let's assume the user is in a wizard, and we don't know whether274// his changes should end up in the base state ultimately or not...
3 unmodified lines
278// the inverse of all the changes made in the wizard279let inverseChanges = []280281fork = produce(282 fork,283 draft => {284 draft.age = 33285 },286 // The third argument to produce is a callback to which the patches will be fed287 (patches, inversePatches) => {288 changes.push(...patches)289 inverseChanges.push(...inversePatches)290 }282 fork,283 draft => {284 draft.age = 33285 },286 // The third argument to produce is a callback to which the patches will be fed287 (patches, inversePatches) => {288 changes.push(...patches)289 inverseChanges.push(...inversePatches)290 }291)292293// In the meantime, our original state is replaced, as, for example,294// some changes were received from the server295state = produce(state, draft => {296 draft.name = "Michel"296 draft.name = "Michel"297})298299// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!300state = applyPatches(state, changes)301302// state now contains the changes from both code paths!303expect(state).toEqual({304 name: "Michel", // changed by the server305 age: 33 // changed by the wizard304 name: "Michel", // changed by the server305 age: 33 // changed by the wizard306})307308// Finally, even after finishing the wizard, the user might change his mind and undo his changes...309state = applyPatches(state, inverseChanges)310expect(state).toEqual({311 name: "Michel", // Not reverted312 age: 32 // Reverted311 name: "Michel", // Not reverted312 age: 32 // Reverted313})314```315316The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string. This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:317318```json319[320 {321 "op": "replace",322 "path": ["profile"],323 "value": {"name": "Veria", "age": 5}324 },325 {"op": "remove", "path": ["tags", 3]}320 {321 "op": "replace",322 "path": ["profile"],323 "value": {"name": "Veria", "age": 5}324 },325 {"op": "remove", "path": ["tags", 3]}326]327```328329```json330[331 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},332 {"op": "add", "path": ["tags", 3], "value": "kiddo"}331 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},332 {"op": "add", "path": ["tags", 3], "value": "kiddo"}333]334```335336For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)
7 unmodified lines
344```javascript345import produce from "immer"346347const user = {348 name: "michel",349 todos: []348 name: "michel",349 todos: []350}351352const loadedUser = await produce(user, async function(draft) {353 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()353 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()354})355```356357_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._
5 unmodified lines
363```javascript364import {createDraft, finishDraft} from "immer"365366const user = {367 name: "michel",368 todos: []367 name: "michel",368 todos: []369}370371const draft = createDraft(user)372draft.todos = await (await window.fetch("http://host/" + draft.name)).json()
11 unmodified lines
384It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:385386```javascript387const userReducer = produce((draft, action) => {388 switch (action.type) {389 case "renameUser":390 // OK: we modify the current state391 draft.users[action.payload.id].name = action.payload.name392 return draft // same as just 'return'393 case "loadUsers":394 // OK: we return an entirely new state395 return action.payload396 case "adduser-1":397 // NOT OK: This doesn't do change the draft nor return a new state!398 // It doesn't modify the draft (it just redeclares it)399 // In fact, this just doesn't do anything at all400 draft = {users: [...draft.users, action.payload]}401 return402 case "adduser-2":403 // NOT OK: modifying draft *and* returning a new state404 draft.userCount += 1405 return {users: [...draft.users, action.payload]}406 case "adduser-3":407 // OK: returning a new state. But, unnecessary complex and expensive408 return {409 userCount: draft.userCount + 1,410 users: [...draft.users, action.payload]411 }412 case "adduser-4":413 // OK: the immer way414 draft.userCount += 1415 draft.users.push(action.payload)416 return417 }388 switch (action.type) {389 case "renameUser":390 // OK: we modify the current state391 draft.users[action.payload.id].name = action.payload.name392 return draft // same as just 'return'393 case "loadUsers":394 // OK: we return an entirely new state395 return action.payload396 case "adduser-1":397 // NOT OK: This doesn't do change the draft nor return a new state!398 // It doesn't modify the draft (it just redeclares it)399 // In fact, this just doesn't do anything at all400 draft = {users: [...draft.users, action.payload]}401 return402 case "adduser-2":403 // NOT OK: modifying draft *and* returning a new state404 draft.userCount += 1405 return {users: [...draft.users, action.payload]}406 case "adduser-3":407 // OK: returning a new state. But, unnecessary complex and expensive408 return {409 userCount: draft.userCount + 1,410 users: [...draft.users, action.payload]411 }412 case "adduser-4":413 // OK: the immer way414 draft.userCount += 1415 draft.users.push(action.payload)416 return417 }418})419```420421_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._
3 unmodified lines
425So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:426427```javascript428produce({}, draft => {429 // don't do anything429 // don't do anything430})431```432433Versus:434435```javascript436produce({}, draft => {437 // Try to return undefined from the producer438 return undefined437 // Try to return undefined from the producer438 return undefined439})440```441442The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.
3 unmodified lines
446```javascript447import produce, {nothing} from "immer"448449const state = {450 hello: "world"450 hello: "world"451}452453produce(state, draft => {})454produce(state, draft => undefined)
29 unmodified lines
484import {original} from "immer"485486const baseState = {users: [{name: "Richie"}]}487const nextState = produce(baseState, draftState => {488 original(draftState.users) // is === baseState.users488 original(draftState.users) // is === baseState.users489})490```491492Just want to know if a value is a proxied instance? Use the `isDraft` function!
2 unmodified lines
495import {isDraft} from "immer"496497const baseState = {users: [{name: "Bobby"}]}498const nextState = produce(baseState, draft => {499 isDraft(draft) // => true500 isDraft(draft.users) // => true501 isDraft(draft.users[0]) // => true499 isDraft(draft) // => true500 isDraft(draft.users) // => true501 isDraft(draft.users[0]) // => true502})503isDraft(nextState) // => false504```505
30 unmodified lines
536```js537import {immerable} from "immer"538539class Foo {540 [immerable] = true // Option 1540 [immerable] = true // Option 1541542 constructor() {543 this[immerable] = true // Option 2544 }542 constructor() {543 this[immerable] = true // Option 2544 }545}546547Foo[immerable] = true // Option 3548```
5 unmodified lines
554Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:555556```js557const state = {558 set: new Set(),559 map: new Map()558 set: new Set(),559 map: new Map()560}561const nextState = produce(state, draft => {562 // Don't use any Set methods, as that mutates the instance!563 draft.set.add("foo") // ❌562 // Don't use any Set methods, as that mutates the instance!563 draft.set.add("foo") // ❌564565 // 1. Instead, clone the set (just once)566 const newSet = new Set(draft.set) // ✅565 // 1. Instead, clone the set (just once)566 const newSet = new Set(draft.set) // ✅567568 // 2. Mutate the clone (just in this producer)569 newSet.add("foo")568 // 2. Mutate the clone (just in this producer)569 newSet.add("foo")570571 // 3. Update the draft with the new set572 draft.set = newSet571 // 3. Update the draft with the new set572 draft.set = newSet573574 // Similarly, don't use any Map methods.575 draft.map.set("foo", "bar") // ❌574 // Similarly, don't use any Map methods.575 draft.map.set("foo", "bar") // ❌576577 // 1. Instead, clone the map (just once)578 const newMap = new Map(draft.map) // ✅577 // 1. Instead, clone the map (just once)578 const newMap = new Map(draft.map) // ✅579580 // 2. Mutate it581 newMap.set("foo", "bar")580 // 2. Mutate it581 newMap.set("foo", "bar")582583 // 3. Update the draft584 draft.map = newMap583 // 3. Update the draft584 draft.map = newMap585})586```587588## TypeScript or Flow
5 unmodified lines
594```ts595import produce from "immer"596597interface State {598 readonly x: number598 readonly x: number599}600601// `x` cannot be modified here602const state: State = {603 x: 0603 x: 0604}605606const newState = produce(state, draft => {607 // `x` can be modified here608 draft.x++607 // `x` can be modified here608 draft.x++609})610611// `newState.x` cannot be modified here612```
5 unmodified lines
618```ts619import produce, {Draft} from "immer"620621interface State {622 readonly x: number622 readonly x: number623}624625// `x` cannot be modified here626const state: State = {627 x: 0627 x: 0628}629630const increment = produce((draft: Draft<State>, inc: number) => {631 // `x` can be modified here632 draft.x += inc631 // `x` can be modified here632 draft.x += inc633})634635const newState = increment(state, 2)636// `newState.x` cannot be modified here
12 unmodified lines
6491. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.650651## Cool things built with immer652653- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_654- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_655- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_656- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_657- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_658- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_659- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_660- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_661- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_662- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_663- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_664- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_665- ... and [many more](https://www.npmjs.com/browse/depended/immer)653- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_654- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_655- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_656- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_657- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_658- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_659- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_660- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_661- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_662- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_663- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_664- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_665- ... and [many more](https://www.npmjs.com/browse/depended/immer)666667## How does Immer work?668669Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).
6 unmodified lines
676import produce from "immer"677678// object mutations679const todosObj = {680 id1: {done: false, body: "Take out the trash"},681 id2: {done: false, body: "Check Email"}680 id1: {done: false, body: "Take out the trash"},681 id2: {done: false, body: "Check Email"}682}683684// add685const addedTodosObj = produce(todosObj, draft => {686 draft["id3"] = {done: false, body: "Buy bananas"}686 draft["id3"] = {done: false, body: "Buy bananas"}687})688689// delete690const deletedTodosObj = produce(todosObj, draft => {691 delete draft["id1"]691 delete draft["id1"]692})693694// update695const updatedTodosObj = produce(todosObj, draft => {696 draft["id1"].done = true696 draft["id1"].done = true697})698699// array mutations700const todosArray = [701 {id: "id1", done: false, body: "Take out the trash"},702 {id: "id2", done: false, body: "Check Email"}701 {id: "id1", done: false, body: "Take out the trash"},702 {id: "id2", done: false, body: "Check Email"}703]704705// add706const addedTodosArray = produce(todosArray, draft => {707 draft.push({id: "id3", done: false, body: "Buy bananas"})707 draft.push({id: "id3", done: false, body: "Buy bananas"})708})709710// delete711const deletedTodosArray = produce(todosArray, draft => {712 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)713 // or (slower):714 // return draft.filter(todo => todo.id !== "id1")712 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)713 // or (slower):714 // return draft.filter(todo => todo.id !== "id1")715})716717// update718const updatedTodosArray = produce(todosArray, draft => {719 draft[draft.findIndex(todo => todo.id === "id1")].done = true719 draft[draft.findIndex(todo => todo.id === "id1")].done = true720})721```722723## Performance
5 unmodified lines
729![performance.png](images/performance.png)730731Most important observation:732733- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.734- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)735- Generating patches doesn't significantly slow immer down736- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.733- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.734- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)735- Generating patches doesn't significantly slow immer down736- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.737738## Migration739740**Immer 2.\* -> 3.0**
52 unmodified lines