pitfalls.md
This file
Path
docs/pitfalls.md
29 lines · 2.1 KiB · Markdown
Last changed by
feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–7why, one step back1---2id: pitfalls3title: Pitfalls4---56<div id="codefund"><!-- fallback content --></div>7Merge pull request #423 from medifle/patch-1Michel Weststratebefore adoption60c4a4f
line 8why, one step back81. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](https://immerjs.github.io/immer/docs/return).Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 9–12why, one step back91. 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.feat: rewrote Map and Set implementation, code base cleanupMichel Weststratebefore adoption1913fe8
lines 13–29why, one step back131. Note that data that comes from the closure, and not from the base state, will never be drafted, even when the data has become part of the new draft:1415```javascript16function onReceiveTodo(todo) {17 const nextTodos = produce(todos, draft => {18 draft.todos[todo.id] = todo19 // Note, because 'todo' is coming from external, and not from the 'draft',20 // it isn't draft so the following modification affects the original todo!21 draft.todos[todo.id].done = true2223 // The reason for this, is that it means that the behavior of the 2 lines above24 // is equivalent to code, making this whole process more consistent25 todo.done = true26 draft.todos[todo.id] = todo27 })28}29```