Skip to content
Myr

Docs website

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 12298be · Browse files · 18 files+101 added−191 removed
This commit

State

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

Diff stats

18 files+101 added−191 removed

  • other:+101 added−191 removed

18 files+101 added−191 removed

modified:docs/api.md+33 added-1 removed
modified:docs/async.md+1 added-1 removed
modified:docs/built-with.md+14 added
modified:docs/curried-produce.md-15 removed
deleted:docs/doc1.md-130 removed
1---2id: doc13title: Latin-ish4sidebar_label: Example Page5---67<div id="codefund"><!-- fallback content --></div>89- NPM: `npm install immer`10- Yarn: `yarn add immer`11- CDN: Exposed global is `immer`12 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`13 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`1415---1617## External resources1819- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)20- 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)21- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)22- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)23- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate24- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)2526# Pitfalls27281. 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).291. 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.301. 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.311. 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)})`321. 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.3334## Cool things built with immer3536- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_37- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_38- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_39- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_40- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_41- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_42- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_43- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_44- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_45- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_46- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_47- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_48- ... and [many more](https://www.npmjs.com/browse/depended/immer)4950## How does Immer work?5152Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).5354## Example patterns.5556_For those who have to go back to thinking in object updates :-)_5758```javascript59import produce from "immer"6061// object mutations62const todosObj = {63 id1: {done: false, body: "Take out the trash"},64 id2: {done: false, body: "Check Email"}65}6667// add68const addedTodosObj = produce(todosObj, draft => {69 draft["id3"] = {done: false, body: "Buy bananas"}70})7172// delete73const deletedTodosObj = produce(todosObj, draft => {74 delete draft["id1"]75})7677// update78const updatedTodosObj = produce(todosObj, draft => {79 draft["id1"].done = true80})8182// array mutations83const todosArray = [84 {id: "id1", done: false, body: "Take out the trash"},85 {id: "id2", done: false, body: "Check Email"}86]8788// add89const addedTodosArray = produce(todosArray, draft => {90 draft.push({id: "id3", done: false, body: "Buy bananas"})91})9293// delete94const deletedTodosArray = produce(todosArray, draft => {95 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)96 // or (slower):97 // return draft.filter(todo => todo.id !== "id1")98})99100// update101const updatedTodosArray = produce(todosArray, draft => {102 draft[draft.findIndex(todo => todo.id === "id1")].done = true103})104```105106## Migration107108**Immer 2.\* -> 3.0**109110In your producers, make sure you're not treating `this` as the draft. (see here: https://github.com/immerjs/immer/issues/308)111112Upgrade to `typescript@^3.4` if you're a TypeScript user.113114**Immer 1.\* -> 2.0**115116Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.117118**Immer 2.1 -> 2.2**119120When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.121122## FAQ123124## Credits125126Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.127128## Donations129130A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)
modified:docs/faq.md+10 added-8 removed
modified:docs/installation.md-16 removed
11 unmodified lines
12- CDN: Exposed global is `immer`13 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`14 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`1516## Importing immer1718`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:1920```javascript21import produce from "immer"22import {produce} from "immer"2324const {produce} = require("immer")25const produce = require("immer").produce26const produce = require("immer").default2728import unleashTheMagic from "immer"29import {produce as unleashTheMagic} from "immer"30```3116## Immer on older JavaScript environments?1718By 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 (if < v0.59 or when using the Hermes engine) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.
modified:docs/introduction.md+2 added-4 removed
23 unmodified lines
24![immer-hd.png](/immer/img/immer.png)2526Using 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).2728A 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.28## Quick Example2930## Example3130```javascript31import produce from "immer"3233const baseState = [
12 unmodified lines
46 draftState[1].done = true47})48```4952The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.50The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will a new immutable tree that reflects all changes made to `draftState` (and strucurally sharing the things that weren't changed).5152Head to the [next section](produce) to further dive into `produce`.5354## Benefits
9 unmodified lines
modified:docs/performance.md+2 added-2 removed
3 unmodified lines
4---56<div id="codefund"><!-- fallback content --></div>78Here 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.8Here is a [simple benchmark](https://github.com/immerjs/immer/blob/master/__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.910Something that isn't reflected in the numbers above, but in reality, Immer is sometimes significantly _faster_ than a hand written reducer. The reason for that is that Immer will detect "no-op" state changes, and return the original state if nothing actually changed, which can avoid a lot of re-renderings for example. Cases are known where simply applying immer solved critical performance issues.1112These tests were executed on Node 10.15.1. Use `yarn test:perf` to reproduce them locally.1314![performance.png](images/performance.png)14![performance.png](/immer/img/performance.png)1516Most important observation:1718- 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.
3 unmodified lines
modified:docs/pitfalls.md+6 added
2 unmodified lines
3title: Pitfalls4---56<div id="codefund"><!-- fallback content --></div>781. 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).91. 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.101. 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.111. 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)})`121. 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.
modified:docs/resources.md+8 added
2 unmodified lines
3title: External resources4---56<div id="codefund"><!-- fallback content --></div>78- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)9- 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)10- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)11- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)12- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate13- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)14- [Talk: Immer, Immutability and the Wonderful World of Proxies](https://www.youtube.com/watch?v=4Nb9Gwp2L24) + [slides](https://jsnation-proxies.surge.sh/), JSNation 2019, Michel Weststrate
modified:docs/support.md+4 added
2 unmodified lines
3title: Supporting immer4---56<div id="codefund"><!-- fallback content --></div>78Immer currently has 350.000 dependents on GitHub, and has almost 10.000.000 downloads per month. However, only the first 2 days of development has been sponsored (by Mendix), and all the development and maintenance after that has been a labor of love.910If you are enjoying Immer, and you are grateful for the package, or want to ensure it's longevity, consider sponsoring the open collective on https://opencollective.com/immer or make a one time donation using [PayPal](https://www.paypal.me/michelweststrate).
modified:website/i18n/en.json+4 added-7 removed
19 unmodified lines
20 },21 "curried-produce": {22 "title": "Curried producers"23 },24 "doc1": {25 "title": "Latin-ish",26 "sidebar_label": "Example Page"27 },24 "example-reducer": {25 "title": "Example Reducer"26 },27 "example-setstate": {
43 unmodified lines
71 "sidebar_label": "TypeScript / Flow"72 }73 },74 "links": {79 "Docs": "Docs",80 "Help": "Help"75 "Documentation": "Documentation",76 "GitHub": "GitHub",77 "Support Immer": "Support Immer"78 },79 "categories": {80 "Basics": "Basics",81 "Advanced Features": "Advanced Features",85 "Reources": "Reources"82 "Resources": "Resources"83 }84 },85 "pages-strings": {86 "Help Translate|recruit community translators for your project": "Help Translate",
4 unmodified lines
modified:website/static/img/immer-logo.pngbinary

A binary file, modified.

modified:website/sidebars.json+3 added-3 removed
1{2 "Immer": {3 "Basics": ["introduction", "installation", "produce", "curried-produce", "api", "example-reducer", "example-setstate"],4 "Advanced Features": ["return", "patches", "freezing", "original", "async", "complex-objects"],5 "Reources": ["resources", "faq", "pitfalls", "built-with", "sponsor"]3 "Basics": ["introduction", "installation", "produce", "curried-produce", "example-reducer", "example-setstate"],4 "Advanced Features": ["api", "typescript", "return", "patches", "freezing", "original", "async", "complex-objects"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }7}
modified:website/siteConfig.js+8 added-1 removed
26 unmodified lines
27 // e.g., for the https://JoelMarcey.github.io site, it would be set like...28 // organizationName: 'JoelMarcey'2930 // For no header links in the top nav bar -> headerLinks: [],31 headerLinks: [{doc: "doc1", label: "Docs"}, {page: "help", label: "Help"}],31 headerLinks: [32 {33 doc: "introduction",34 label: "Documentation"35 },36 {href: "https://github.com/immerjs/immer", label: "GitHub"},37 {doc: "support", label: "Support Immer"}38 ],3940 /* path to images for header/footer */41 headerIcon: "img/favicon.ico",42 footerIcon: "img/favicon.ico",
61 unmodified lines
modified:package.json+2 added-1 removed
17 unmodified lines
18 "watch": "jest --watch",19 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",20 "build": "rimraf dist/ && yarn-or-npm bili && yarn-or-npm typed",21 "typed": "cpx 'src/immer.{d.ts,js.flow}' dist -v",22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages"22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",23 "start": "cd website && yarn start"24 },25 "husky": {26 "hooks": {27 "pre-commit": "pretty-quick --staged"
61 unmodified lines
modified:readme.md+4 added-2 removed
6 unmodified lines
7_Create the next immutable state tree by simply modifying the current tree_89Winner of the "Breakthrough of the year" [React open source award](https://osawards.com/react/) and "Most impactful contribution" [JavaScript open source award](https://osawards.com/javascript/) in 20191011# Documentation1213Can now be found on https://immerjs.github.io/immer/1415### [Release notes](https://github.com/immerjs/immer/releases)1617Did 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>1415---