Skip to content
Myr

`immer` -> `produce`. Implements #24

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 2fee7f9 · Browse files · 9 files+74 added−75 removed
This commit

State

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

Diff stats

9 files+74 added−75 removed

  • tests:+34 added−34 removed
  • other:+40 added−41 removed

9 files+74 added−75 removed

modified:__performance_tests__/todo.js+6 added-6 removed
modified:__tests__/base.js+28 added-28 removed
8 unmodified lines
9runBaseTest("es5 (autofreeze)", immerEs5, true)1011function runBaseTest(name, lib, freeze) {12 describe(`base functionality - ${name}`, () => {13 const immer = lib.default13 const produce = lib.default14 let baseState15 let origBaseState1617 beforeEach(() => {
1 unmodified line
19 origBaseState = baseState = createBaseState()20 })2122 it("should return the original without modifications", () => {23 const nextState = immer(baseState, () => {})23 const nextState = produce(baseState, () => {})24 expect(nextState).toBe(baseState)25 })2627 it("should return the original without modifications when reading stuff", () => {28 const nextState = immer(baseState, s => {28 const nextState = produce(baseState, s => {29 expect(s.aProp).toBe("hi")30 expect(s.anObject.nested).toMatchObject({yummie: true})31 })32 expect(nextState).toBe(baseState)33 })3435 it("should not return any value: thunk", () => {36 const warning = jest.spyOn(console, "warn")37 immer(baseState, () => ({bad: "don't do this"}))38 immer(baseState, () => [1, 2, 3])39 immer(baseState, () => false)40 immer(baseState, () => "")37 produce(baseState, () => ({bad: "don't do this"}))38 produce(baseState, () => [1, 2, 3])39 produce(baseState, () => false)40 produce(baseState, () => "")4142 expect(warning).toHaveBeenCalledTimes(4)43 warning.mockClear()44 })4546 it("should return a copy when modifying stuff", () => {47 const nextState = immer(baseState, s => {47 const nextState = produce(baseState, s => {48 s.aProp = "hello world"49 })50 expect(nextState).not.toBe(baseState)51 expect(baseState.aProp).toBe("hi")
4 unmodified lines
5657 if (58 ("should preserve type",59 () => {60 const nextState = immer(baseState, s => {60 const nextState = produce(baseState, s => {61 expect(Array.isArray(s)).toBe(true)62 expect(s.protoType).toBe(Object)63 s.anArray.push(3)64 s.aProp = "hello world"
4 unmodified lines
69 expect(nextState.protoType).toBe(Object)70 })71 )72 it("deep change bubbles up", () => {73 const nextState = immer(baseState, s => {73 const nextState = produce(baseState, s => {74 s.anObject.nested.yummie = false75 })76 expect(nextState).not.toBe(baseState)77 expect(nextState.anObject).not.toBe(baseState.anObject)
2 unmodified lines
80 expect(nextState.anArray).toBe(baseState.anArray)81 })8283 it("can add props", () => {84 const nextState = immer(baseState, s => {84 const nextState = produce(baseState, s => {85 s.anObject.cookie = {tasty: true}86 })87 expect(nextState).not.toBe(baseState)88 expect(nextState.anObject).not.toBe(baseState.anObject)
1 unmodified line
90 expect(nextState.anObject.cookie).toEqual({tasty: true})91 })9293 it("can delete props", () => {94 const nextState = immer(baseState, s => {94 const nextState = produce(baseState, s => {95 delete s.anObject.nested96 })97 expect(nextState).not.toBe(baseState)98 expect(nextState.anObject).not.toBe(baseState.anObject)99 expect(nextState.anObject.nested).toBe(undefined)100 })101102 it("ignores single non-modification", () => {103 const nextState = immer(baseState, s => {103 const nextState = produce(baseState, s => {104 s.aProp = "hi"105 })106 expect(nextState).toBe(baseState)107 })108109 it("processes single modification", () => {110 const nextState = immer(baseState, s => {110 const nextState = produce(baseState, s => {111 s.aProp = "hello"112 s.aProp = "hi"113 })114 expect(nextState).not.toBe(baseState)115 expect(nextState).toEqual(baseState)116 })117118 it("should support reading arrays", () => {119 const nextState = immer(baseState, s => {119 const nextState = produce(baseState, s => {120 s.anArray.slice()121 })122 expect(nextState.anArray).toBe(baseState.anArray)123 expect(nextState).toBe(baseState)124 })125126 it("should support changing arrays", () => {127 const nextState = immer(baseState, s => {127 const nextState = produce(baseState, s => {128 s.anArray[3] = true129 })130 expect(nextState).not.toBe(baseState)131 expect(nextState.anArray).not.toBe(baseState.anArray)132 expect(nextState.anArray[3]).toEqual(true)133 })134135 it("should support changing arrays - 2", () => {136 const nextState = immer(baseState, s => {136 const nextState = produce(baseState, s => {137 s.anArray.splice(1, 1, "a", "b")138 })139 expect(nextState).not.toBe(baseState)140 expect(nextState.anArray).not.toBe(baseState.anArray)
7 unmodified lines
148 ])149 })150151 it("can delete array items", () => {152 const nextState = immer(baseState, s => {152 const nextState = produce(baseState, s => {153 s.anArray.length = 3154 })155 expect(nextState).not.toBe(baseState)156 expect(nextState.anObject).toBe(baseState.anObject)
1 unmodified line
158 expect(nextState.anArray).toEqual([3, 2, {c: 3}])159 })160161 it("should support sorting arrays", () => {162 const nextState = immer(baseState, s => {162 const nextState = produce(baseState, s => {163 s.anArray[2].c = 4164 s.anArray.sort()165 s.anArray[3].c = 5166 })
2 unmodified lines
169 expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])170 })171172 it("should expose property descriptors", () => {173 const nextState = immer([], s => {173 const nextState = produce([], s => {174 expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(undefined)175 s.unshift("x")176 expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({177 configurable: true,
13 unmodified lines
191 })192 })193194 it("should support sorting arrays - 2", () => {195 const nextState = immer(baseState, s => {195 const nextState = produce(baseState, s => {196 s.anArray.unshift("x")197 s.anArray[3].c = 4198 s.anArray.sort()199 s.anArray[3].c = 5
11 unmodified lines
211 ])212 })213214 it("should updating inside arrays", () => {215 const nextState = immer(baseState, s => {215 const nextState = produce(baseState, s => {216 s.anArray[2].test = true217 })218 expect(nextState).not.toBe(baseState)219 expect(nextState.anArray).not.toBe(baseState.anArray)220 expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])221 })222223 it("reusing object should work", () => {224 const nextState = immer(baseState, s => {224 const nextState = produce(baseState, s => {225 const obj = s.anObject226 delete s.anObject227 s.messy = obj228 })
12 unmodified lines
241 expect(nextState.messy.nested).toBe(baseState.anObject.nested)242 })243244 it("refs should be transparent", () => {245 const nextState = immer(baseState, s => {245 const nextState = produce(baseState, s => {246 const obj = s.anObject247 s.aProp = "hello"248 delete s.anObject249 obj.coffee = true
15 unmodified lines
265 expect(nextState.messy.nested).toBe(baseState.anObject.nested)266 })267268 it("should allow setting to undefined a defined draft property", () => {269 const nextState = immer(baseState, s => {269 const nextState = produce(baseState, s => {270 s.aProp = undefined271 })272 expect(nextState).not.toBe(baseState)273 expect(baseState.aProp).toBe("hi")
3 unmodified lines
277 // ES implementation does't protect against all outside modifications, just some..278 if (name === "proxy") {279 it("should revoke the proxy of the baseState after immer function is executed", () => {280 let proxy281 const nextState = immer(baseState, s => {281 const nextState = produce(baseState, s => {282 proxy = s283 s.aProp = "hello"284 })285 expect(nextState).not.toBe(baseState)
14 unmodified lines
300 }301302 it("should revoke the proxy of the baseState after immer function is executed - 2", () => {303 let proxy304 const nextState = immer(baseState, s => {304 const nextState = produce(baseState, s => {305 proxy = s.anObject306 })307 expect(nextState).toBe(baseState)308 expect(() => {
5 unmodified lines
314 }).toThrowError(/revoked/)315 })316317 it("should reflect all changes made in the draft immediately", () => {318 immer(baseState, draft => {318 produce(baseState, draft => {319 draft.anArray[0] = 5320 draft.anArray.unshift("test")321 // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols322 expect(draft.anArray.slice()).toMatchObject([
41 unmodified lines
modified:__tests__/frozen.js+4 added-4 removed
6 unmodified lines
7runBaseTest("es5", immerEs5)89function runBaseTest(name, lib) {10 describe("auto freeze - " + name, () => {11 const immer = lib.default11 const produce = lib.default12 const baseState = {13 object: {a: 1},14 array: [1, 2]15 }1617 it("should freeze objects after modifications", () => {18 expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen19 const next = immer(baseState, draft => {19 const next = produce(baseState, draft => {20 draft.object.c = 221 })22 expect(Object.isFrozen(next.object)).toBe(true)23 expect(Object.isFrozen(next)).toBe(true)
5 unmodified lines
29 })3031 it("should freeze arrays after modifications", () => {32 expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen33 const next = immer(baseState, draft => {33 const next = produce(baseState, draft => {34 draft.array.push(3)35 })36 expect(Object.isFrozen(next.object)).toBe(false) // not touched37 expect(Object.isFrozen(next)).toBe(true)
8 unmodified lines
46 const a = []47 const b = {a: a}48 Object.freeze(a)49 Object.freeze(b)50 const n = immer(b, draft => {50 const n = produce(b, draft => {51 draft.c = true52 draft.a.push(3)53 })54 expect(n).toEqual({c: true, a: [3]})
3 unmodified lines
modified:__tests__/readme.js+2 added-2 removed
1"use strict"2import immer from ".."2import produce from ".."34describe("readme example", () => {5 it("works", () => {6 const baseState = [
6 unmodified lines
13 done: false14 }15 ]1617 const nextState = immer(baseState, draft => {17 const nextState = produce(baseState, draft => {18 draft.push({todo: "Tweet about it"})19 draft[1].done = true20 })21
15 unmodified lines
added:images/proxy.pngbinary

A binary file, added.

added:images/tree.pngbinary

A binary file, added.

modified:es5.js+2 added-2 removed
13 unmodified lines
14 * @param {any} baseState - the state to start with15 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified16 * @returns {any} a new state, or the base state if nothing was modified17 */18function immer(baseState, thunk) {18function produce(baseState, thunk) {19 let finalizing = false20 let finished = false21 const descriptors = {}22 const states = []
228 unmodified lines
251 autoFreeze = enableAutoFreeze252}253254createHiddenProperty(exports, "__esModule", true)255module.exports.default = immer255module.exports.default = produce256module.exports.setAutoFreeze = setAutoFreeze
modified:immer.js+3 added-3 removed
79 unmodified lines
80 * @param {any} baseState - the state to start with81 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84function immer(baseState, thunk) {84function produce(baseState, thunk) {85 const revocableProxies = []8687 class State {88 constructor(parent, base) {
143 unmodified lines
232 if(autoFreeze) {233 Object.freeze(value)234 }235 * */236 autoFreeze && Object.freeze(value);236 autoFreeze && Object.freeze(value)237 return value238}239240/**
10 unmodified lines
251252Object.defineProperty(exports, "__esModule", {253 value: true254})255module.exports.default = immer255module.exports.default = produce256module.exports.setAutoFreeze = setAutoFreeze
modified:readme.md+29 added-30 removed
15 unmodified lines
16Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.17It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.1819The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.20Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.20Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.21This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.2223![immer.png](images/immer.png)2425Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).25Using Immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).2627A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.2829## Installation
1 unmodified line
31`npm install immer`3233## API3435The immer package exposes a single function:35The Immer package exposes a single function, which typically, but not necessarily is called `produce`:3637`immer(currentState, fn: (draftState) => void): nextState`37`produce(currentState, producer: (draftState) => void): nextState`3839## Example4041```javascript42import immer from "immer"42import produce from "immer"4344const baseState = [45 {46 todo: "Learn typescript",47 done: true48 },49 {50 todo: "Try immer",50 todo: "Try Immer",51 done: false52 }53]5455const nextState = immer(baseState, draftState => {55const nextState = produce(baseState, draftState => {56 draftState.push({ todo: "Tweet about it" })57 draftState[1].done = true58})59```6061The interesting thing about `immer` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.61The interesting thing about `produce` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.6263```javascript64// the new item is only added to the next state,65// base state is unmodified
9 unmodified lines
75// changed data not (dûh)76expect(nextState[1]).not.toBe(baseState[1])77```7879## Using immer on older JavaScript environments79## Using Immer on older JavaScript environments8081By default `immer` tries to use proxies for optimal performance.81By default Immer tries to use proxies for optimal performance.82However, on older JavaScript engines `Proxy` is not available.83For example, Microsoft Internet Explorer or React Native on Android.84In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:8586```javascript87import immer from "immer/es5"87import produce from "immer/es5"88```8990## Benefits9192* Use the language© to construct create your next state93* Use JavaScript native arrays and object94* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozen94* Automatic immutability; any state tree produced by Immer will by defualt be deeply frozen95* Strongly typed, no string based paths etc96* Deep updates are trivial97* Small, dependency free library with minimal api surface98* No accidental mutations of current state, but intentional mutations of a draft state99100## Auto freezing101102 Immer automatically freezes any state trees that are modified using `immer.103 This protects against accidental modifications of the state tree outside of an immer function.102 Immer automatically freezes any state trees that are modified using `produce`.103 This protects against accidental modifications of the state tree outside of a producer function.104 This comes with a performance impact, so it is recommended to disable this option in production.105 It is by default enabled.106107 Use `setAutoFreeze(true / false)` to turn this feature on or off.
2 unmodified lines
110111Here is a simple example of the difference that this approach could make in practice.112The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)113114_Note, this is just a sample application of the `immer` package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_114_Note, this is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_115116```javascript117const todo = (state, action) => {118 switch (action.type) {
33 unmodified lines
152 }153}154```155156After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):156When using Immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):157158```javascript159import immer from 'immer'159import produce from 'immer'160161const todos = (state = [], action) =>162 // immer produces nextState from draftState and returns it163 immer(state, draftState => {162 // produce produces nextState from draftState and returns it163 produce(state, draftState => {164 switch (action.type) {165 case 'ADD_TODO':166 draftState.push({167 id: action.id,
8 unmodified lines
176 }177 })178```179180Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).180Creating middleware or a reducer wrapper that applies `produce` automatically is left as exercise for the reader :-).181182---183184Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their immer counter part.184Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their Immer counter part.185These examples are semantically equivalent and produce the exact same state.186187```javascript188// Plain reducer
6 unmodified lines
195}196197// With immer198function insertItem(array, action) {199 return immer(array, draft => {199 return produce(array, draft => {200 draft.splice(action.index, 0, action.item)201 })202}203
6 unmodified lines
210}211212// With immer213function removeItem(array, action) {214 return immer(array, draft => {214 return produce(array, draft => {215 draft.splice(action.index, 1)216 })217}218
3 unmodified lines
222 if(index !== action.index) {223 // This isn't the item we care about - keep it as-is224 return item;225 }226226 // Otherwise, this is the one we want - return an updated value227 return {228 ...item,229 ...action.item
2 unmodified lines
232}233234// With immer235function updateObjectInArray(array, action) {237 return immer(array, draft => {236 return produce(array, draft => {237 draft[action.index] = { ...item, ...action.item}239 // Alternatively, since arbitrarily deep updates are supported:238 // Or, alternatively:239 // Object.assign(draft[action.index], action.item)240 })241}242```
5 unmodified lines
248249## Pitfalls:250251* Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` or whatever complex object from the draft state, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.253* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!254* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`252* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `produce`!253* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer or read from the `currentState` rather than the `draftState`254* Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.255256## Performance257259Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.258Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.259This test takes 100.000 todo items, and updates 10.000 of them.260_Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.261262These tests were executed on Node 8.4.0.
5 unmodified lines
268* The _mutate_, and _deepclone, mutate_ benchmarks establish a baseline on how expensive changing the data is, without immutability (or structural sharing in the deep clone case).269* The _reduce_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.270* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.271* 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)273* The ES5 implementation of immer is significantly slower. For most reducers this won't matter, but reducers that process large amounts of data might benefit from not (or only partially) using an immer producer. Luckily, immer is fully opt-in.272* The ES5 implementation of Immer is significantly slower. For most reducers this won't matter, but reducers that process large amounts of data might benefit from not (or only partially) using an Immer producer. Luckily, Immer is fully opt-in.273* The peeks in the _frozen_ versions of _just mutate_, _deepclone_ and _naive reducer_ come from the fact that they recursively freeze the full state tree, while the other test cases only freeze the modified parts of the tree.274275## Credits276
1 unmodified line