readme.md
This file
Path
readme.md
788 lines · 30.8 KiB · Markdown
Last changed by
docs: Readme fixesMichel Weststratebefore adoption980474a
History of this fileTake it
The walk stopped after 200 commits: lines older than cbdd98c point at it.
v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 1–4why, one step back1<img src="images/immer-logo.png" height="200px" align="right"/>23# Immer4docs: remove install size badgeMichel Weststratebefore adoption7820eee
line 5why, one step back5[](https://www.npmjs.com/package/immer) [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [](https://travis-ci.org/mweststrate/immer) [](https://coveralls.io/github/mweststrate/immer?branch=master) [](https://github.com/prettier/prettier) [](https://www.paypal.me/michelweststrate)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 6–8why, one step back67_Create the next immutable state tree by simply modifying the current tree_8[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
lines 9–10why, one step back9Winner of the "breakthrough of the year" [open source award](https://osawards.com/react/) in 201910feat: Immer now has it's own Github org, `immerjs`Michel Weststratebefore adoption17d69c3
line 11why, one step back11### [Release notes](https://github.com/immerjs/immer/releases)chore: add "Release notes" link to readmealeclarsonbefore adoption1803dd8
line 12why, one step back12v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 13–16why, one step back13Did 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---16chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 17–21why, one step back17- NPM: `npm install immer`18- Yarn: `yarn add immer`19- CDN: Exposed global is `immer`20 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`21 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 22–24why, one step back2223---24chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 25–26why, one step back25- 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)26- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 27–29why, one step back2728Immer (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.29Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 30why, one step back30The 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 31–33why, one step back313233Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 34why, one step back34Using 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).v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 35–37why, one step back3536A 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.37Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 38–39why, one step back38## External resources39chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 40–44why, one step back40- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)41- 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)42- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststratedocs: added ForwardJS talk by swyxMichel Weststratebefore adoption984434e
line 45why, one step back45- [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/)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
line 46why, one step back46v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 47–96why, one step back47## API4849The Immer package exposes a default function that does all the work.5051`produce(currentState, producer: (draftState) => void): nextState`5253There is also a curried overload that is explained [below](#currying).5455## Example5657```javascript58import produce from "immer"5960const baseState = [61 {62 todo: "Learn typescript",63 done: true64 },65 {66 todo: "Try immer",67 done: false68 }69]7071const nextState = produce(baseState, draftState => {72 draftState.push({todo: "Tweet about it"})73 draftState[1].done = true74})75```7677The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.7879```javascript80// the new item is only added to the next state,81// base state is unmodified82expect(baseState.length).toBe(2)83expect(nextState.length).toBe(3)8485// same for the changed 'done' prop86expect(baseState[1].done).toBe(false)87expect(nextState[1].done).toBe(true)8889// unchanged data is structurally shared90expect(nextState[0]).toBe(baseState[0])91// changed data not (dûh)92expect(nextState[1]).not.toBe(baseState[1])93```9495## Benefits96chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 97–102why, one step back97- Immutability with normal JavaScript objects and arrays. No new APIs to learn!98- Strongly typed, no string based paths selectors etc.99- Structural sharing out of the box100- Object freezing out of the box101- Deep updates are a breeze102- Boilerplate reduction. Less noise, more concise code.docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 103why, one step back103- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 104–183why, one step back104105Read further to see all these benefits explained.106107## Reducer Example108109Here is a simple example of the difference that Immer could make in practice.110111```javascript112// Redux reducer113// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114const byId = (state, action) => {115 switch (action.type) {116 case RECEIVE_PRODUCTS:117 return {118 ...state,119 ...action.products.reduce((obj, product) => {120 obj[product.id] = product121 return obj122 }, {})123 }124 default:125 return state126 }127}128```129130After using Immer, that simply becomes:131132```javascript133import produce from "immer"134135const byId = (state, action) =>136 produce(state, draft => {137 switch (action.type) {138 case RECEIVE_PRODUCTS:139 action.products.forEach(product => {140 draft[product.id] = product141 })142 }143 })144```145146Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.147148Creating Redux reducer is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).149150_Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._151152## React.setState example153154Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):155156```javascript157/**158 * Classic React.setState with a deep merge159 */160onBirthDayClick1 = () => {161 this.setState(prevState => ({162 user: {163 ...prevState.user,164 age: prevState.user.age + 1165 }166 }))167}168169/**170 * ...But, since setState accepts functions,171 * we can just create a curried producer and further simplify!172 */173onBirthDayClick2 = () => {174 this.setState(175 produce(draft => {176 draft.user.age += 1177 })178 )179}180```181182## Currying183Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 184why, one step back184Passing 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 185–236why, one step back185186For example:187188```javascript189// mapper will be of signature (state, index) => state190const mapper = produce((draft, index) => {191 draft.index = index192})193194// example usage195console.dir([{}, {}, {}].map(mapper))196//[{index: 0}, {index: 1}, {index: 2}])197```198199This mechanism can also nicely be leveraged to further simplify our example reducer:200201```javascript202import produce from 'immer'203204const byId = produce((draft, action) => {205 switch (action.type) {206 case RECEIVE_PRODUCTS:207 action.products.forEach(product => {208 draft[product.id] = product209 })210 return211 })212 }213})214```215216Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).217218If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:219220```javascript221import produce from "immer"222223const byId = produce(224 (draft, action) => {225 switch (action.type) {226 case RECEIVE_PRODUCTS:227 action.products.forEach(product => {228 draft[product.id] = product229 })230 return231 }232 },233 {234 1: {id: 1, name: "product-1"}235 }236)Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 237–240why, one step back237```238239##### Fun with currying240chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 241why, one step back241A 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:Added some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 242–248why, one step back242243```javascript244import produce from "immer"245const spread = produce(Object.assign)246247const base = {x: 1, y: 1}248chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 249why, one step back249console.log({...base, y: 1} === base) // falseAdded some external resources to readmeMichel Weststratebefore adoptionc018c49
lines 250–251why, one step back250console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced251console.log(spread(base, {y: 2}) === base) // false, produced a new object as it shouldv1.7.2Michel Weststratebefore adoptioncbdd98c
lines 252–255why, one step back252```253254## Patches255chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 256why, one step back256During 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 257–259why, one step back257258Patches are useful in few scenarios:259chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 260–262why, one step back260- To exchange incremental updates with other parties, for example over websockets261- For debugging / traces, to see precisely how state is changed over time262- As basis for undo/redo or as an approach to replay changes on a slightly different state treev1.7.2Michel Weststratebefore adoptioncbdd98c
line 263why, one step back263chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 264–265why, one step back264To 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:265v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 266–274why, one step back266```javascript267import produce, {applyPatches} from "immer"268269let state = {270 name: "Micheal",271 age: 32272}273274// Let's assume the user is in a wizard, and we don't know whetherSpell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 275why, one step back275// his changes should end up in the base state ultimately or not...v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 276–293why, one step back276let fork = state277// all the changes the user made in the wizard278let changes = []279// the inverse of all the changes made in the wizard280let inverseChanges = []281282fork = produce(283 fork,284 draft => {285 draft.age = 33286 },287 // The third argument to produce is a callback to which the patches will be fed288 (patches, inversePatches) => {289 changes.push(...patches)290 inverseChanges.push(...inversePatches)291 }292)293Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 294why, one step back294// In the meantime, our original state is replaced, as, for example,v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 295–305why, one step back295// some changes were received from the server296state = produce(state, draft => {297 draft.name = "Michel"298})299300// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!301state = applyPatches(state, changes)302303// state now contains the changes from both code paths!304expect(state).toEqual({305 name: "Michel", // changed by the serverchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 306why, one step back306 age: 33 // changed by the wizardv1.7.2Michel Weststratebefore adoptioncbdd98c
lines 307–312why, one step back307})308309// Finally, even after finishing the wizard, the user might change his mind and undo his changes...310state = applyPatches(state, inverseChanges)311expect(state).toEqual({312 name: "Michel", // Not revertedchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 313why, one step back313 age: 32 // Revertedv1.7.2Michel Weststratebefore adoptioncbdd98c
lines 314–316why, one step back314})315```316chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 317why, one step back317The 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:v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 318–320why, one step back318319```json320[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 321–326why, one step back321 {322 "op": "replace",323 "path": ["profile"],324 "value": {"name": "Veria", "age": 5}325 },326 {"op": "remove", "path": ["tags", 3]}v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 327–331why, one step back327]328```329330```json331[chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 332–333why, one step back332 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},333 {"op": "add", "path": ["tags", 3], "value": "kiddo"}v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 334–336why, one step back334]335```336Added link to immer patch articleMichel Weststratebefore adoption255d135
lines 337–338why, one step back337For 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)338Added note about compressing patchesMichel Weststratebefore adoption7cae55b
lines 339–340why, one step back339Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.340Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 341why, one step back341## Async producersv1.7.2Michel Weststratebefore adoptioncbdd98c
line 342why, one step back342Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 343why, one step back343It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:v1.7.2Michel Weststratebefore adoptioncbdd98c
line 344why, one step back344Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 345–353why, one step back345```javascript346import produce from "immer"347348const user = {349 name: "michel",350 todos: []351}352353const loadedUser = await produce(user, async function(draft) {docs: fixed error in docsMichel Weststratebefore adoption42b14bd
line 354why, one step back354 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 355–380why, one step back355})356```357358_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._359360## `createDraft` and `finishDraft`361362`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:363364```javascript365import {createDraft, finishDraft} from "immer"366367const user = {368 name: "michel",369 todos: []370}371372const draft = createDraft(user)373draft.todos = await (await window.fetch("http://host/" + draft.name)).json()374const loadedUser = finishDraft(draft)375```376377Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.378379_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._380v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 381–425why, one step back381## Returning data from producers382383It 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`.384385It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:386387```javascript388const userReducer = produce((draft, action) => {389 switch (action.type) {390 case "renameUser":391 // OK: we modify the current state392 draft.users[action.payload.id].name = action.payload.name393 return draft // same as just 'return'394 case "loadUsers":395 // OK: we return an entirely new state396 return action.payload397 case "adduser-1":398 // NOT OK: This doesn't do change the draft nor return a new state!399 // It doesn't modify the draft (it just redeclares it)400 // In fact, this just doesn't do anything at all401 draft = {users: [...draft.users, action.payload]}402 return403 case "adduser-2":404 // NOT OK: modifying draft *and* returning a new state405 draft.userCount += 1406 return {users: [...draft.users, action.payload]}407 case "adduser-3":408 // OK: returning a new state. But, unnecessary complex and expensive409 return {410 userCount: draft.userCount + 1,411 users: [...draft.users, action.payload]412 }413 case "adduser-4":414 // OK: the immer way415 draft.userCount += 1416 draft.users.push(action.payload)417 return418 }419})420```421422_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._423424## Producing `undefined` using `nothing`425chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 426why, one step back426So, 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`:v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 427–442why, one step back427428```javascript429produce({}, draft => {430 // don't do anything431})432```433434Versus:435436```javascript437produce({}, draft => {438 // Try to return undefined from the producer439 return undefined440})441```442chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 443why, one step back443The 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 444–447why, one step back444445However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:446447```javascriptchore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 448why, one step back448import produce, {nothing} from "immer"v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 449–453why, one step back449450const state = {451 hello: "world"452}453chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 454–455why, one step back454produce(state, draft => {})455produce(state, draft => undefined)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 456–457why, one step back456// Both return the original state: { hello: "world"}457chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 458why, one step back458produce(state, draft => nothing)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 459–463why, one step back459// Produces a new state, 'undefined'460```461462N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.463Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 464–479why, one step back464## Inline shortcuts using `void`465466Draft 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.467468In 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`.469470```javascript471// Single mutation472produce(draft => void (draft.user.age += 1))473474// Multiple mutations475produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))476```477478Code 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.479v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 480–484why, one step back480## Extracting the original object from a proxied instance481482Immer 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.483484```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 485why, one step back485const baseState = {users: [{name: "Richie"}]}v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 486–490why, one step back486const nextState = produce(baseState, draftState => {487 original(draftState.users) // is === baseState.users488})489```490Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 491–493why, one step back491Just want to know if a value is a proxied instance? Use the `isDraft` function!492493```jschore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 494why, one step back494import {isDraft} from "immer"Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 495why, one step back495chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 496why, one step back496const baseState = {users: [{name: "Bobby"}]}Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 497why, one step back497const nextState = produce(baseState, draft => {chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 498–499why, one step back498 isDraft(draft) // => true499 isDraft(draft.users) // => trueMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
lines 500–504why, one step back500 isDraft(draft.users[0]) // => true501})502isDraft(nextState) // => false503```504Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 505why, one step back505## Auto freezingv1.7.2Michel Weststratebefore adoptioncbdd98c
line 506why, one step back506Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 507why, one step back507Immer 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 508–510why, one step back508509## Immer on older JavaScript environments?510Update readme.md (#334)Noitidartbefore adoptionab7a44b
line 511why, one step back511By 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 (< v0.59) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 512–514why, one step back512513## Importing immer514Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 515why, one step back515`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:v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 516–518why, one step back516517```javascript518import produce from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 519why, one step back519import {produce} from "immer"v1.7.2Michel Weststratebefore adoptioncbdd98c
line 520why, one step back520chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 521why, one step back521const {produce} = require("immer")v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 522–525why, one step back522const produce = require("immer").produce523const produce = require("immer").default524525import unleashTheMagic from "immer"chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 526why, one step back526import {produce as unleashTheMagic} from "immer"v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 527–528why, one step back527```528docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 529why, one step back529## Supported object typesv1.7.2Michel Weststratebefore adoptioncbdd98c
line 530why, one step back530docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 531–535why, one step back531Plain objects and arrays are always drafted by Immer.532533Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.534535```js[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
line 536why, one step back536import {immerable} from "immer"docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 537–538why, one step back537538class Foo {[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
line 539why, one step back539 [immerable] = true // Option 1docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
line 540why, one step back540[docs] Added OSAward to the readmeMichel Weststratebefore adoption0431653
lines 541–543why, one step back541 constructor() {542 this[immerable] = true // Option 2543 }docs: elaborate on immerable symbolAlec Larsonbefore adoption9e12f56
lines 544–547why, one step back544}545546Foo[immerable] = true // Option 3547```chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 548why, one step back548docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 549why, one step back549For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.v1.7.2Michel Weststratebefore adoptioncbdd98c
line 550why, one step back550docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 551why, one step back551When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.v1.7.2Michel Weststratebefore adoptioncbdd98c
line 552why, one step back552docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 553why, one step back553Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:v1.7.2Michel Weststratebefore adoptioncbdd98c
line 554why, one step back554docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 555why, one step back555```jsv1.7.2Michel Weststratebefore adoptioncbdd98c
line 556why, one step back556const state = {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 557–558why, one step back557 set: new Set(),558 map: new Map()v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 559–560why, one step back559}560const nextState = produce(state, draft => {docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 561–562why, one step back561 // Don't use any Set methods, as that mutates the instance!562 draft.set.add("foo") // ❌v1.7.2Michel Weststratebefore adoptioncbdd98c
line 563why, one step back563docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 564–565why, one step back564 // 1. Instead, clone the set (just once)565 const newSet = new Set(draft.set) // ✅v1.7.2Michel Weststratebefore adoptioncbdd98c
line 566why, one step back566docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 567–568why, one step back567 // 2. Mutate the clone (just in this producer)568 newSet.add("foo")v1.7.2Michel Weststratebefore adoptioncbdd98c
line 569why, one step back569docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 570–571why, one step back570 // 3. Update the draft with the new set571 draft.set = newSetv1.7.2Michel Weststratebefore adoptioncbdd98c
line 572why, one step back572docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 573–583why, one step back573 // Similarly, don't use any Map methods.574 draft.map.set("foo", "bar") // ❌575576 // 1. Instead, clone the map (just once)577 const newMap = new Map(draft.map) // ✅578579 // 2. Mutate it580 newMap.set("foo", "bar")581582 // 3. Update the draft583 draft.map = newMapv1.7.2Michel Weststratebefore adoptioncbdd98c
lines 584–585why, one step back584})585```docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
line 586why, one step back586Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 587–604why, one step back587## TypeScript or Flow588589The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.590591The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:592593```ts594import produce from "immer"595596interface State {597 readonly x: number598}599600// `x` cannot be modified here601const state: State = {602 x: 0603}604docs: Update readmeMichel Weststratebefore adoptionfe2473f
line 605why, one step back605const newState = produce(state, draft => {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 606–614why, one step back606 // `x` can be modified here607 draft.x++608})609610// `newState.x` cannot be modified here611```612613This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!614docs: Update readmeMichel Weststratebefore adoptionfe2473f
line 615why, one step back615For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 616why, one step back616docs: Update readmeMichel Weststratebefore adoptionfe2473f
lines 617–637why, one step back617```ts618import produce, {Draft} from "immer"619620interface State {621 readonly x: number622}623624// `x` cannot be modified here625const state: State = {626 x: 0627}628629const increment = produce((draft: Draft<State>, inc: number) => {630 // `x` can be modified here631 draft.x += inc632})633634const newState = increment(state, 2)635// `newState.x` cannot be modified here636```637docs: Readme fixesMichel Weststratebefore adoption980474a
line 638why, one step back638**Note:** Immer v1.9+ supports TypeScript v3.1+ only.docs: Update readmeMichel Weststratebefore adoptionfe2473f
line 639why, one step back639docs: Readme fixesMichel Weststratebefore adoption980474a
line 640why, one step back640**Note:** Immer v3.0+ supports TypeScript v3.4+ only.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 641why, one step back641docs: mention the "immerable" symbolaleclarsonbefore adoptionf72f69b
lines 642–648why, one step back642# Pitfalls6436441. 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).6451. 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.6461. 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.6471. 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)})`6481. 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 649–651why, one step back649650## Cool things built with immer651chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 652–659why, one step back652- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_653- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_654- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_655- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_656- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_657- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_658- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_659- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_Merge pull request #285 from epeli/patch-1Michel Weststratebefore adoptionaf55671
line 660why, one step back660- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse Redux reducers with Typescript_docs: add redux-ts-utils to "cool things made with immer"Kenneth Powersbefore adoption0b6960a
line 661why, one step back661- [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_docs: add react-state-treeAlec Larsonbefore adoptiondfcd543
line 662why, one step back662- [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_chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
line 663why, one step back663- ... and [many more](https://www.npmjs.com/browse/depended/immer)v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 664–722why, one step back664665## How does Immer work?666667Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).668669## Example patterns.670671_For those who have to go back to thinking in object updates :-)_672673```javascript674import produce from "immer"675676// object mutations677const todosObj = {678 id1: {done: false, body: "Take out the trash"},679 id2: {done: false, body: "Check Email"}680}681682// add683const addedTodosObj = produce(todosObj, draft => {684 draft["id3"] = {done: false, body: "Buy bananas"}685})686687// delete688const deletedTodosObj = produce(todosObj, draft => {689 delete draft["id1"]690})691692// update693const updatedTodosObj = produce(todosObj, draft => {694 draft["id1"].done = true695})696697// array mutations698const todosArray = [699 {id: "id1", done: false, body: "Take out the trash"},700 {id: "id2", done: false, body: "Check Email"}701]702703// add704const addedTodosArray = produce(todosArray, draft => {705 draft.push({id: "id3", done: false, body: "Buy bananas"})706})707708// delete709const deletedTodosArray = produce(todosArray, draft => {710 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)711 // or (slower):712 // return draft.filter(todo => todo.id !== "id1")713})714715// update716const updatedTodosArray = produce(todosArray, draft => {717 draft[draft.findIndex(todo => todo.id === "id1")].done = true718})719```720721## Performance722Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 723why, one step back723Here 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 724–730why, one step back724725These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.726727728729Most important observation:730chore: run prettier on readmealeclarsonbefore adoptiona7a8cfa
lines 731–734why, one step back731- 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.732- 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)733- Generating patches doesn't significantly slow immer down734- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 735–737why, one step back735736## Migration737docs: stub migration guideMichel Weststratebefore adoption3149a4d
lines 738–741why, one step back738**Immer 2.\* -> 3.0**739740TODO741Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 742–744why, one step back742**Immer 1.\* -> 2.0**743744Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.docs: Update readmeMichel Weststratebefore adoptionfe2473f
lines 745–748why, one step back745746**Immer 2.1 -> 2.2**747748When 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.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 749–783why, one step back749750## FAQ751752_(for those who skimmed the above instead of actually reading)_753754**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**755756A: Yes757758**Q: Does Immer support deep updates?**759760A: Yes761762**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**763764A: Yes765766**Q: Can I typecheck my data structures when using Immer?**767768A: Yes769770**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**771772A: Yes773774**Q: Is it fast?**775776A: Yes777778**Q: Idea! Can Immer freeze the state for me?**779780A: Yes781782## Credits783Spell checking (#217)Oscar Nordquistbefore adoptionf2f4f2c
line 784why, one step back784Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.v1.7.2Michel Weststratebefore adoptioncbdd98c
lines 785–788why, one step back785786## Donations787788A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)