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
Provenance
- Commit
f72f69b- Tree
32e41a3- Author
aleclarson <alec.stanford.larson@gmail.com>- Committer
aleclarson <alec.stanford.larson@gmail.com>- Parent
f7e0d35
1 file changed+37 added−50 removed
modified:readme.md+37 added-50 removed
95 unmodified lines96 - 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 [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)101 102 Read further to see all these benefits explained.103 104 ## Reducer Example428 unmodified lines533 import unleashTheMagic from "immer"534 import {produce as unleashTheMagic} from "immer"535 ```536 537-## Limitations537+## Supported object types538 539-Immer supports the following types of data:539+Only 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.540 541-1. All kinds of primitive values542-1. `Date` instances, but: only if not mutated, see below543-1. Arrays, but: non-standard attributes are not supported (like: `array.test = "Test"`)544-1. Plain objects (objects that have as prototype either `null` or `Object`)545-1. Functions, assuming they aren't mutated546-1. 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.541+For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.542 548-# Pitfalls543+When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.544 550-1. 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).551-1. 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.552-1. 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)553-1. 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.554-1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.555-1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.556-1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`557-1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.558-1. Immer does not support built-in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:545+Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:546 560-```javascript547+```js548 const state = {562- title: "hello",563- tokenSet: new Set()549+ set: new Set(),550+ map: new Map()551 }565-552 const 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") // ❌555 571- // 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) // ✅558 580-Or 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")561 582-```javascript583-const state = {584- users: new Map(["michel", {name: "miche"}])585-}562+ // 3. Update the draft with the new set563+ draft.set = newSet564 587-const 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") // ❌567+568+ // 1. Instead, clone the map (just once)569+ const newMap = new Map(draft.map) // ✅570+571+ // 2. Mutate it572+ newMap.set("foo", "bar")573+574+ // 3. Update the draft575+ draft.map = newMap576 })577 ```578 579+# Pitfalls580+581+1. 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).582+1. 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.583+1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.584+1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.585+1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`586+1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.587+588 ## Cool things built with immer589 590 - [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