Skip to content
Myr

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

1 file+80 added−80 removed

modified:readme.md+80 added-80 removed
8 unmodified lines
9Did 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>1011---1213* 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>`1819---2021* 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)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.
5 unmodified lines
32A 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 resources3536* 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 Weststrate4142## API4344The Immer package exposes a default function that does all the work.
43 unmodified lines
88```8990## Benefits9192* 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.99100Read further to see all these benefits explained.101102## Reducer Example
129 unmodified lines
232```233234##### Fun with currying235236A random fun example just for inspiration:237a 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)).238Quick example:236A 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:237238```javascript239import produce from "immer"240const spread = produce(Object.assign)241242const base = {x: 1, y: 1}243246console.log({...base, y: 1} === base) // false244console.log({...base, y: 1} === base) // false245console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced246console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should247```248249## Patches250253During 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.251During 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.252253Patches 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 tree254261To 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: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 tree258259To 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:260261```javascript262import produce, {applyPatches} from "immer"263264let state = {
32 unmodified lines
297298// state now contains the changes from both code paths!299expect(state).toEqual({300 name: "Michel", // changed by the server304 age: 33 // changed by the wizard301 age: 33 // changed by the wizard302})303304// Finally, even after finishing the wizard, the user might change his mind and undo his changes...305state = applyPatches(state, inverseChanges)306expect(state).toEqual({307 name: "Michel", // Not reverted311 age: 32 // Reverted308 age: 32 // Reverted309})310```311315The 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.316This 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:312The 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:313314```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```324325```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```331332For 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 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.386There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:385So, 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`:386387```javascript388produce({}, draft => {389 // don't do anything
8 unmodified lines
398 return undefined399})400```401403The 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.402The 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.403404However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:405406```javascript410import produce, { nothing } from "immer"407import produce, {nothing} from "immer"408409const state = {410 hello: "world"411}412416produce(state, (draft) => {})417produce(state, (draft) => undefined)413produce(state, draft => {})414produce(state, draft => undefined)415// Both return the original state: { hello: "world"}416420produce(state, (draft) => nothing)417produce(state, draft => nothing)418// Produces a new state, 'undefined'419```420421N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.
2 unmodified lines
424425Immer 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.426427```js431const baseState = { users: [{ name: "Richie" }] };428const baseState = {users: [{name: "Richie"}]}429const nextState = produce(baseState, draftState => {430 original(draftState.users) // is === baseState.users431})432```433434Just want to know if a value is a proxied instance? Use the `isDraft` function!435436```js440import { isDraft } from "immer";437import {isDraft} from "immer"438442const baseState = { users: [{ name: "Bobby" }] };439const baseState = {users: [{name: "Bobby"}]}440const nextState = produce(baseState, draft => {444 isDraft(draft) // => true445 isDraft(draft.users) // => true441 isDraft(draft) // => true442 isDraft(draft.users) // => true443 isDraft(draft.users[0]) // => true444})445isDraft(nextState) // => false446```
29 unmodified lines
476// Single mutation477produce(draft => void (draft.user.age += 1))478479// Multiple mutations483produce(draft => void (draft.user.age += 1, draft.user.height = 186))480produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))481```482483Code 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 lines
488489The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:490491```ts495import produce from 'immer'492import produce from "immer"493494interface State {498 readonly x: number495 readonly x: number496}497498// `x` cannot be modified here499const state: State = {503 x: 0500 x: 0501}502503const newState = produce<State>(state, draft => {507 // `x` can be modified here508 draft.x++504 // `x` can be modified here505 draft.x++506})507508// `newState.x` cannot be modified here509```
11 unmodified lines
521`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:522523```javascript524import produce from "immer"528import { produce } from "immer"525import {produce} from "immer"526530const { produce } = require("immer")527const {produce} = require("immer")528const produce = require("immer").produce529const produce = require("immer").default530531import unleashTheMagic from "immer"535import { produce as unleashTheMagic } from "immer"532import {produce as unleashTheMagic} from "immer"533```534535## Limitations536537Immer supports the following types of data:5385391. All kinds of primitive values5401. `Date` instances, but: only if not mutated, see below5411. Arrays, but: non-standard attributes are not supported (like: `array.test = "Test"`)5421. Plain objects (objects that have as prototype either `null` or `Object`)
9 unmodified lines
5521. 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.5531. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.5541. 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)})`5551. 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.5581. 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:5561. 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:557558```javascript559const state = {560 title: "hello",
17 unmodified lines
578Or a deep update in maps (well, don't use maps for this use case, but as an example):579580```javascript581const state = {584 users: new Map(["michel", { name: "miche" }])582 users: new Map(["michel", {name: "miche"}])583}584585const 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```598598599## Cool things built with immer600601* [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)610611## How does Immer work?612613Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).
59 unmodified lines
673![performance.png](images/performance.png)674675Most important observation:676677* 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.681682## FAQ683684_(for those who skimmed the above instead of actually reading)_
36 unmodified lines