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
Provenance
- Commit
615ca6f- Tree
728e2cb- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
96f2b2e
1 file changed+211 added−211 removed
modified:readme.md+211 added-211 removed
4 unmodified lines5 [](https://www.npmjs.com/package/immer) [](https://travis-ci.org/immerjs/immer) [](https://coveralls.io/github/immerjs/immer?branch=master) [](https://bundlephobia.com/result?p=immer) [](https://github.com/prettier/prettier) [](https://www.paypal.me/michelweststrate)6 7 _Create the next immutable state tree by simply modifying the current tree_8 9-Winner of the "breakthrough of the year" [open source award](https://osawards.com/react/) in 20199+Winner 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 201910 11 ### [Release notes](https://github.com/immerjs/immer/releases)12 13 Did 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>14 15 ---16 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>`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>`22 23 ---24 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)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)27 28 Immer (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.29 30 The 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 lines36 A 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.37 38 ## External resources39 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/)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/)46 47 ## API48 49 The Immer package exposes a default function that does all the work.7 unmodified lines57 ```javascript58 import produce from "immer"59 60 const 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 ]70 71 const 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 ```76 77 The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.15 unmodified lines93 ```94 95 ## Benefits96 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 [](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 [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)104 105 Read further to see all these benefits explained.106 107 ## Reducer Example3 unmodified lines111 ```javascript112 // Redux reducer113 // Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114 const 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 ```129 130 After using Immer, that simply becomes:1 unmodified line132 ```javascript133 import produce from "immer"134 135 const 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 ```145 146 Notice 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 lines157 /**158 * Classic React.setState with a deep merge159 */160 onBirthDayClick1 = () => {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 }168 169 /**170 * ...But, since setState accepts functions,171 * we can just create a curried producer and further simplify!172 */173 onBirthDayClick2 = () => {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 ```181 182 ## Currying4 unmodified lines187 188 ```javascript189 // mapper will be of signature (state, index) => state190 const mapper = produce((draft, index) => {191- draft.index = index191+ draft.index = index192 })193 194 // example usage195 console.dir([{}, {}, {}].map(mapper))5 unmodified lines201 ```javascript202 import produce from "immer"203 204 const 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 ```214 215 Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).3 unmodified lines219 ```javascript220 import produce from "immer"221 222 const 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 ```237 238 ##### Fun with currying16 unmodified lines255 During 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.256 257 Patches are useful in few scenarios:258 259-- 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 tree262 263 To 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:264 265 ```javascript266 import produce, {applyPatches} from "immer"267 268 let state = {269- name: "Micheal",270- age: 32269+ name: "Micheal",270+ age: 32271 }272 273 // 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 lines278 // the inverse of all the changes made in the wizard279 let inverseChanges = []280 281 fork = 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 )292 293 // In the meantime, our original state is replaced, as, for example,294 // some changes were received from the server295 state = produce(state, draft => {296- draft.name = "Michel"296+ draft.name = "Michel"297 })298 299 // When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!300 state = applyPatches(state, changes)301 302 // state now contains the changes from both code paths!303 expect(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 })307 308 // Finally, even after finishing the wizard, the user might change his mind and undo his changes...309 state = applyPatches(state, inverseChanges)310 expect(state).toEqual({311- name: "Michel", // Not reverted312- age: 32 // Reverted311+ name: "Michel", // Not reverted312+ age: 32 // Reverted313 })314 ```315 316 The 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:317 318 ```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 ```328 329 ```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 ```335 336 For 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 lines344 ```javascript345 import produce from "immer"346 347 const user = {348- name: "michel",349- todos: []348+ name: "michel",349+ todos: []350 }351 352 const 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 ```356 357 _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 lines363 ```javascript364 import {createDraft, finishDraft} from "immer"365 366 const user = {367- name: "michel",368- todos: []367+ name: "michel",368+ todos: []369 }370 371 const draft = createDraft(user)372 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()11 unmodified lines384 It 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:385 386 ```javascript387 const 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 ```420 421 _Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._3 unmodified lines425 So, 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`:426 427 ```javascript428 produce({}, draft => {429- // don't do anything429+ // don't do anything430 })431 ```432 433 Versus:434 435 ```javascript436 produce({}, draft => {437- // Try to return undefined from the producer438- return undefined437+ // Try to return undefined from the producer438+ return undefined439 })440 ```441 442 The 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 lines446 ```javascript447 import produce, {nothing} from "immer"448 449 const state = {450- hello: "world"450+ hello: "world"451 }452 453 produce(state, draft => {})454 produce(state, draft => undefined)29 unmodified lines484 import {original} from "immer"485 486 const baseState = {users: [{name: "Richie"}]}487 const nextState = produce(baseState, draftState => {488- original(draftState.users) // is === baseState.users488+ original(draftState.users) // is === baseState.users489 })490 ```491 492 Just want to know if a value is a proxied instance? Use the `isDraft` function!2 unmodified lines495 import {isDraft} from "immer"496 497 const baseState = {users: [{name: "Bobby"}]}498 const 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 })503 isDraft(nextState) // => false504 ```505 30 unmodified lines536 ```js537 import {immerable} from "immer"538 539 class Foo {540- [immerable] = true // Option 1540+ [immerable] = true // Option 1541 542- constructor() {543- this[immerable] = true // Option 2544- }542+ constructor() {543+ this[immerable] = true // Option 2544+ }545 }546 547 Foo[immerable] = true // Option 3548 ```5 unmodified lines554 Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:555 556 ```js557 const state = {558- set: new Set(),559- map: new Map()558+ set: new Set(),559+ map: new Map()560 }561 const 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") // ❌564 565- // 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) // ✅567 568- // 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")570 571- // 3. Update the draft with the new set572- draft.set = newSet571+ // 3. Update the draft with the new set572+ draft.set = newSet573 574- // 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") // ❌576 577- // 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) // ✅579 580- // 2. Mutate it581- newMap.set("foo", "bar")580+ // 2. Mutate it581+ newMap.set("foo", "bar")582 583- // 3. Update the draft584- draft.map = newMap583+ // 3. Update the draft584+ draft.map = newMap585 })586 ```587 588 ## TypeScript or Flow5 unmodified lines594 ```ts595 import produce from "immer"596 597 interface State {598- readonly x: number598+ readonly x: number599 }600 601 // `x` cannot be modified here602 const state: State = {603- x: 0603+ x: 0604 }605 606 const newState = produce(state, draft => {607- // `x` can be modified here608- draft.x++607+ // `x` can be modified here608+ draft.x++609 })610 611 // `newState.x` cannot be modified here612 ```5 unmodified lines618 ```ts619 import produce, {Draft} from "immer"620 621 interface State {622- readonly x: number622+ readonly x: number623 }624 625 // `x` cannot be modified here626 const state: State = {627- x: 0627+ x: 0628 }629 630 const increment = produce((draft: Draft<State>, inc: number) => {631- // `x` can be modified here632- draft.x += inc631+ // `x` can be modified here632+ draft.x += inc633 })634 635 const newState = increment(state, 2)636 // `newState.x` cannot be modified here12 unmodified lines649 1. 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.650 651 ## Cool things built with immer652 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)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)666 667 ## How does Immer work?668 669 Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).6 unmodified lines676 import produce from "immer"677 678 // object mutations679 const 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 }683 684 // add685 const addedTodosObj = produce(todosObj, draft => {686- draft["id3"] = {done: false, body: "Buy bananas"}686+ draft["id3"] = {done: false, body: "Buy bananas"}687 })688 689 // delete690 const deletedTodosObj = produce(todosObj, draft => {691- delete draft["id1"]691+ delete draft["id1"]692 })693 694 // update695 const updatedTodosObj = produce(todosObj, draft => {696- draft["id1"].done = true696+ draft["id1"].done = true697 })698 699 // array mutations700 const 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 ]704 705 // add706 const 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 })709 710 // delete711 const 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 })716 717 // update718 const updatedTodosArray = produce(todosArray, draft => {719- draft[draft.findIndex(todo => todo.id === "id1")].done = true719+ draft[draft.findIndex(todo => todo.id === "id1")].done = true720 })721 ```722 723 ## Performance5 unmodified lines729 730 731 Most important observation:732 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.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.737 738 ## Migration739 740 **Immer 2.\* -> 3.0**52 unmodified lines