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
Provenance
- Commit
f2f4f2c- Tree
9d7d2c7- Author
Oscar Nordquist <oscar.cv.nordquist@gmail.com>- Committer
Alec Larson <aleclarson@users.noreply.github.com>- Parent
51648ef
1 file changed+21 added−21 removed
modified:readme.md+21 added-21 removed
21 unmodified lines22 * Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)23 24 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.25 26-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.26+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.27 28 29 30-Using 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).30+Using 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).31 32 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.33 34 ## External resources140 unmodified lines175 ```176 177 ## Currying178 179-Passing 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.179+Passing 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.180 181 For example:182 183 ```javascript66 unmodified lines250 251 ## Patches252 253 During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.254-This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.254+This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.255 256 Patches 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 tree260 261 To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used262 to record the incremental updates and (inverse) apply them:263 5 unmodified lines269 age: 32270 }271 272 // 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...274 let fork = state275 // all the changes the user made in the wizard276 let changes = []277 // the inverse of all the changes made in the wizard10 unmodified lines288 inverseChanges.push(...inversePatches)289 }290 )291 292-// 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 server294 state = produce(state, draft => {295 draft.name = "Michel"296 })37 unmodified lines334 Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.335 336 ## Auto freezing337 338-Immer 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.338+Immer 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.339 340 ## Returning data from producers341 342 It 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 lines381 _Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._382 383 ## Producing `undefined` using `nothing`384 385-So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.385+So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.386 There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:387 388 ```javascript389 produce({}, draft => {9 unmodified lines399 return undefined400 })401 ```402 403-The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!403+The problem is that in JavaScript a function that doesn't return anything also returns `undefined`!404 So immer cannot differentiate between those different cases.405 So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.406 407 However, 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 lines458 ## Inline shortcuts using `void`459 460 Draft 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.461 462-In 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`.462+In 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`.463 464 ```javascript465 // Single mutation466 produce(draft => void (draft.user.age += 1))33 unmodified lines500 This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!501 502 ## Immer on older JavaScript environments?503 504-By 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.504+By 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.505 506 ## Importing immer507 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 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:509 510 ```javascript511 import produce from "immer"512 import { produce } from "immer"19 unmodified lines532 # Pitfalls533 534 1. 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).535 1. 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.536-1. 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)536+1. 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)537 1. 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.538-1. 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.538+1. 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.539 1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.540 1. 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)})`541-1. 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.542-1. 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:541+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.542+1. 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:543 544 ```javascript545 const state = {546 title: "hello",13 unmodified lines560 draft.tokenSet = newSet561 })562 ```563 564-Or a deep update in maps (well, don't use maps for this use case, but as example):564+Or a deep update in maps (well, don't use maps for this use case, but as an example):565 566 ```javascript567 const state = {568 users: new Map(["michel", { name: "miche" }])80 unmodified lines649 ```650 651 ## Performance652 653-Here 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.653+Here 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.654 655 These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.656 657 658 659 Most important observation:660 661-* 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 lines696 A: Yes697 698 ## Credits699 700-Special 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.700+Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.701 702 ## Donations703 704 A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)