Skip to content
Myr

Spell checking (#217)

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

Readme improvements by the generous @ntwigs

authored by Oscar Nordquist · committed by Alec Larson · parent 51648ef · Browse files · 1 file+21 added−21 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+21 added−21 removed

  • other:+21 added−21 removed

1 file+21 added−21 removed

modified:readme.md+21 added-21 removed
21 unmodified lines
22* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)2324Immer (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.2526The 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.26The 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.2728![immer-hd.png](images/hd/immer.png)2930Using 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).30Using 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).3132A 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.3334## External resources
140 unmodified lines
175```176177## Currying178179Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.179Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft and any further arguments that were passed to the curried function.180181For example:182183```javascript
66 unmodified lines
250251## Patches252253During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.254This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.254This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.255256Patches are useful in few scenarios:257 * To exchange incremental updates with other parties, for example over websockets258 * For debugging / traces, to see precisely how state is changed over time259 * As basis for undo/redo or as approach to replay changes on a slightly different state tree259 * As basis for undo/redo or as an approach to replay changes on a slightly different state tree260261To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used262to record the incremental updates and (inverse) apply them:263
5 unmodified lines
269 age: 32270}271272// Let's assume the user is in a wizard, and we don't know whether273// his changes should be end up in the base state ultimately or not...273// his changes should end up in the base state ultimately or not...274let fork = state275// all the changes the user made in the wizard276let changes = []277// the inverse of all the changes made in the wizard
10 unmodified lines
288 inverseChanges.push(...inversePatches)289 }290)291292// In the mean time, our original state is replaced, as, for example,292// In the meantime, our original state is replaced, as, for example,293// some changes were received from the server294state = produce(state, draft => {295 draft.name = "Michel"296})
37 unmodified lines
334Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.335336## Auto freezing337338Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.338Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.339340## Returning data from producers341342It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.
38 unmodified lines
381_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._382383## Producing `undefined` using `nothing`384385So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.385So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.386There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:387388```javascript389produce({}, draft => {
9 unmodified lines
399 return undefined400})401```402403The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!403The problem is that in JavaScript a function that doesn't return anything also returns `undefined`!404So immer cannot differentiate between those different cases.405So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.406407However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:
50 unmodified lines
458## Inline shortcuts using `void`459460Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.461462In such cases you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.462In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.463464```javascript465// Single mutation466produce(draft => void (draft.user.age += 1))
33 unmodified lines
500This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!501502## Immer on older JavaScript environments?503504By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.504By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.505506## Importing immer507508`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommend:508`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommended:509510```javascript511import produce from "immer"512import { produce } from "immer"
19 unmodified lines
532# Pitfalls5335341. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).5351. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.5361. Class instances are not, and will not supported first-class supported. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)5361. Class instances are not, and will not have first-class support. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)5371. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.5381. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.5381. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.5391. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.5401. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`5411. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistiguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.5421. Immer does not support built in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:5411. 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.5421. Immer does not support built-in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:543544```javascript545const state = {546 title: "hello",
13 unmodified lines
560 draft.tokenSet = newSet561})562```563564Or a deep update in maps (well, don't use maps for this use case, but as example):564Or a deep update in maps (well, don't use maps for this use case, but as an example):565566```javascript567const state = {568 users: new Map(["michel", { name: "miche" }])
80 unmodified lines
649```650651## Performance652653Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items, and updates 5,000 of them. _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.653Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,000 of them. _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.654655These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.656657![performance.png](images/performance.png)658659Most important observation:660661* Immer with proxies is roughly speaking twice to three times slower as a hand written reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.661* 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.662* 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)663* Generating patches doesn't significantly slow immer down664* The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.665
30 unmodified lines
696A: Yes697698## Credits699700Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.700Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.701702## Donations703704A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)