chore: run prettier on readme
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by aleclarson · committed by aleclarson · parent ab05744 · Browse files · 1 file·+80 added−80 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+80 added−80 removed
- other:+80 added−80 removed
Provenance
- Commit
a7a8cfa- Tree
3a296ff- Author
aleclarson <alec.stanford.larson@gmail.com>- Committer
aleclarson <alec.stanford.larson@gmail.com>- Parent
ab05744
1 file changed+80 added−80 removed
modified:readme.md+80 added-80 removed
8 unmodified lines9 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>10 11 ---12 13-* NPM: `npm install immer`14-* Yarn: `yarn add immer`15-* CDN: Exposed global is `immer`16- * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`17- * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`13+- NPM: `npm install immer`14+- Yarn: `yarn add immer`15+- CDN: Exposed global is `immer`16+ - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`17+ - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`18 19 ---20 21-* 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)22-* Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)21+- 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)22+- 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.5 unmodified lines32 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 resources35 36-* Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)37-* 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)38-* Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)39-* Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)40-* [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate36+- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)37+- 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)38+- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)39+- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)40+- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate41 42 ## API43 44 The Immer package exposes a default function that does all the work.43 unmodified lines88 ```89 90 ## Benefits91 92-* Immutability with normal JavaScript objects and arrays. No new APIs to learn!93-* Strongly typed, no string based paths selectors etc.94-* Structural sharing out of the box95-* Object freezing out of the box96-* Deep updates are a breeze97-* Boilerplate reduction. Less noise, more concise code.98-* Small: bundled and minified: 2KB.92+- Immutability with normal JavaScript objects and arrays. No new APIs to learn!93+- Strongly typed, no string based paths selectors etc.94+- Structural sharing out of the box95+- Object freezing out of the box96+- Deep updates are a breeze97+- Boilerplate reduction. Less noise, more concise code.98+- Small: bundled and minified: 2KB.99 100 Read further to see all these benefits explained.101 102 ## Reducer Example129 unmodified lines232 ```233 234 ##### Fun with currying235 236-A random fun example just for inspiration:237-a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)).238-Quick example:236+A random fun example just for inspiration: a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)). Quick example:237 238 ```javascript239 import produce from "immer"240 const spread = produce(Object.assign)241 242 const base = {x: 1, y: 1}243 246-console.log({...base, y: 1} === base) // false244+console.log({...base, y: 1} === base) // false245 console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced246 console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should247 ```248 249 ## Patches250 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.251+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.252 253 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 an approach to replay changes on a slightly different state tree254 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:255+- To exchange incremental updates with other parties, for example over websockets256+- For debugging / traces, to see precisely how state is changed over time257+- As basis for undo/redo or as an approach to replay changes on a slightly different state tree258 259+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:260+261 ```javascript262 import produce, {applyPatches} from "immer"263 264 let state = {32 unmodified lines297 298 // state now contains the changes from both code paths!299 expect(state).toEqual({300 name: "Michel", // changed by the server304- age: 33 // changed by the wizard301+ age: 33 // changed by the wizard302 })303 304 // Finally, even after finishing the wizard, the user might change his mind and undo his changes...305 state = applyPatches(state, inverseChanges)306 expect(state).toEqual({307 name: "Michel", // Not reverted311- age: 32 // Reverted308+ age: 32 // Reverted309 })310 ```311 315-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.316-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:312+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:313 314 ```json315 [316+ {317+ "op": "replace",318+ "path": ["profile"],319+ "value": {"name": "Veria", "age": 5}320- { "op": "replace", "path": ["profile"], "value": { "name": "Veria", "age": 5 }},321- { "op": "remove", "path": ["tags", 3] }320+ },321+ {"op": "remove", "path": ["tags", 3]}322 ]323 ```324 325 ```json326 [327- { "op": "replace", "path": ["profile"], "value": { "name": "Noa", "age": 6 }},328- { "op": "add", "path": ["tags", 3], "value": "kiddo"},327+ {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},328+ {"op": "add", "path": ["tags", 3], "value": "kiddo"}329 ]330 ```331 332 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)48 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.386-There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`: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. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:386 387 ```javascript388 produce({}, draft => {389 // don't do anything8 unmodified lines398 return undefined399 })400 ```401 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.402+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.403 404 However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:405 406 ```javascript410-import produce, { nothing } from "immer"407+import produce, {nothing} from "immer"408 409 const state = {410 hello: "world"411 }412 416-produce(state, (draft) => {})417-produce(state, (draft) => undefined)413+produce(state, draft => {})414+produce(state, draft => undefined)415 // Both return the original state: { hello: "world"}416 420-produce(state, (draft) => nothing)417+produce(state, draft => nothing)418 // Produces a new state, 'undefined'419 ```420 421 N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.2 unmodified lines424 425 Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.426 427 ```js431-const baseState = { users: [{ name: "Richie" }] };428+const baseState = {users: [{name: "Richie"}]}429 const nextState = produce(baseState, draftState => {430 original(draftState.users) // is === baseState.users431 })432 ```433 434 Just want to know if a value is a proxied instance? Use the `isDraft` function!435 436 ```js440-import { isDraft } from "immer";437+import {isDraft} from "immer"438 442-const baseState = { users: [{ name: "Bobby" }] };439+const baseState = {users: [{name: "Bobby"}]}440 const nextState = produce(baseState, draft => {444- isDraft(draft) // => true445- isDraft(draft.users) // => true441+ isDraft(draft) // => true442+ isDraft(draft.users) // => true443 isDraft(draft.users[0]) // => true444 })445 isDraft(nextState) // => false446 ```29 unmodified lines476 // Single mutation477 produce(draft => void (draft.user.age += 1))478 479 // Multiple mutations483-produce(draft => void (draft.user.age += 1, draft.user.height = 186))480+produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))481 ```482 483 Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.484 3 unmodified lines488 489 The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:490 491 ```ts495-import produce from 'immer'492+import produce from "immer"493 494 interface State {498- readonly x: number495+ readonly x: number496 }497 498 // `x` cannot be modified here499 const state: State = {503- x: 0500+ x: 0501 }502 503 const newState = produce<State>(state, draft => {507- // `x` can be modified here508- draft.x++504+ // `x` can be modified here505+ draft.x++506 })507 508 // `newState.x` cannot be modified here509 ```11 unmodified lines521 `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:522 523 ```javascript524 import produce from "immer"528-import { produce } from "immer"525+import {produce} from "immer"526 530-const { produce } = require("immer")527+const {produce} = require("immer")528 const produce = require("immer").produce529 const produce = require("immer").default530 531 import unleashTheMagic from "immer"535-import { produce as unleashTheMagic } from "immer"532+import {produce as unleashTheMagic} from "immer"533 ```534 535 ## Limitations536 537 Immer supports the following types of data:538+539 1. All kinds of primitive values540 1. `Date` instances, but: only if not mutated, see below541 1. Arrays, but: non-standard attributes are not supported (like: `array.test = "Test"`)542 1. Plain objects (objects that have as prototype either `null` or `Object`)9 unmodified lines552 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.553 1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.554 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)})`555 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.558-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:556+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:557 558 ```javascript559 const state = {560 title: "hello",17 unmodified lines578 Or a deep update in maps (well, don't use maps for this use case, but as an example):579 580 ```javascript581 const state = {584- users: new Map(["michel", { name: "miche" }])582+ users: new Map(["michel", {name: "miche"}])583 }584 585 const nextState = produce(state, draft => {586 const newUsers = new Map(draft.users)587 // mutate the new map and set a _new_ user object588 // but leverage produce again to base the new user object on the original one589+ newUsers.set(590+ "michel",591- newUsers.set("michel", produce(draft.users.get("michel"), draft => {592- draft.name = "michel"593- }))591+ produce(draft.users.get("michel"), draft => {592+ draft.name = "michel"593+ })594+ )595 draft.users = newUsers596 })597 ```598 598-599 ## Cool things built with immer600 601-* [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_602-* [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_603-* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_604-* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_605-* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_606-* [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_607-* [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_608-* [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_609-* ... and [many more](https://www.npmjs.com/browse/depended/immer)601+- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_602+- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_603+- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_604+- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_605+- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_606+- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_607+- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_608+- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_609+- ... and [many more](https://www.npmjs.com/browse/depended/immer)610 611 ## How does Immer work?612 613 Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).59 unmodified lines673 674 675 Most important observation:676 677-* 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.678-* 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)679-* Generating patches doesn't significantly slow immer down680-* The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.677+- 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.678+- 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)679+- Generating patches doesn't significantly slow immer down680+- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.681 682 ## FAQ683 684 _(for those who skimmed the above instead of actually reading)_36 unmodified lines