Skip to content
Myr

docs: mention the "immerable" symbol

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

authored by aleclarson · committed by aleclarson · parent f7e0d35 · Browse files · 1 file+37 added−50 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+37 added−50 removed

  • other:+37 added−50 removed

1 file+37 added−50 removed

modified:readme.md+37 added-50 removed
95 unmodified lines
96- Structural sharing out of the box97- Object freezing out of the box98- Deep updates are a breeze99- Boilerplate reduction. Less noise, more concise code.100- Small: bundled and minified: 2KB.100- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)101102Read further to see all these benefits explained.103104## Reducer Example
428 unmodified lines
533import unleashTheMagic from "immer"534import {produce as unleashTheMagic} from "immer"535```536537## Limitations537## Supported object types538539Immer supports the following types of data:539Only plain objects and arrays are automatically drafted by Immer. This means other object types should never be mutated **unless** you added the exported `immerable` symbol to the object itself, its prototype, or its class constructor. In that case, the object is essentially an immutable plain object with a custom prototype.5405411. All kinds of primitive values5421. `Date` instances, but: only if not mutated, see below5431. Arrays, but: non-standard attributes are not supported (like: `array.test = "Test"`)5441. Plain objects (objects that have as prototype either `null` or `Object`)5451. Functions, assuming they aren't mutated5461. Other value types (like class instances) can be stored in the tree, but note that Immer won't work _inside_ those objects. In other words, if you modify a class instance, this will _not_ result in clone and unmodified original, but just in a modified original.541For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.542548# Pitfalls543When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.5445501. 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).5511. 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.5521. Class instances are not, and will not have first-class support. Read [here](https://github.com/mweststrate/immer/issues/155#issuecomment-407725592) why classes are a conceptual mismatch (and technically extremely challenging)5531. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.5541. 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.5551. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.5561. 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)})`5571. 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:545Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:546560```javascript547```js548const state = {562 title: "hello",563 tokenSet: new Set()549 set: new Set(),550 map: new Map()551}565552const nextState = produce(state, draft => {567 draft.title = draft.title.toUpperCase() // let immer do it's job568 // don't use the operations onSet, as that mutates the instance!569 // draft.tokenSet.add("c1342")553 // Don't use any Set methods, as that mutates the instance!554 draft.set.add("foo") // ❌555571 // instead: clone the set (once!)572 const newSet = new Set(draft.tokenSet)573 // mutate the clone (just in this producer)574 newSet.add("c1342")575 // update the draft with the new set576 draft.tokenSet = newSet577})578```556 // 1. Instead, clone the set (just once)557 const newSet = new Set(draft.set) // ✅558580Or a deep update in maps (well, don't use maps for this use case, but as an example):559 // 2. Mutate the clone (just in this producer)560 newSet.add("foo")561582```javascript583const state = {584 users: new Map(["michel", {name: "miche"}])585}562 // 3. Update the draft with the new set563 draft.set = newSet564587const nextState = produce(state, draft => {588 const newUsers = new Map(draft.users)589 // mutate the new map and set a _new_ user object590 // but leverage produce again to base the new user object on the original one591 newUsers.set(592 "michel",593 produce(draft.users.get("michel"), draft => {594 draft.name = "michel"595 })596 )597 draft.users = newUsers565 // Similarly, don't use any Map methods.566 draft.map.set("foo", "bar") // ❌567568 // 1. Instead, clone the map (just once)569 const newMap = new Map(draft.map) // ✅570571 // 2. Mutate it572 newMap.set("foo", "bar")573574 // 3. Update the draft575 draft.map = newMap576})577```578579# Pitfalls5805811. 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).5821. 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.5831. 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.5841. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.5851. 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)})`5861. 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.587588## Cool things built with immer589590- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_591- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_
119 unmodified lines