pitfalls.md
This file
Path
website/docs/pitfalls.md
115 lines · 5.2 KiB · Markdown
Last changed by
feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
History of this fileTake it
The walk stopped after 200 commits: lines older than ba24aab point at it.
chore: Fix typo (#954)Marc Barbeaubefore adoptionba24aab
lines 1–6why, one step back1---2id: pitfalls3title: Pitfalls4---56<center>chore: docusaurus upgradeMichel Weststratebefore adoption48a91b3
line 7why, one step back7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>chore: Fix typo (#954)Marc Barbeaubefore adoptionba24aab
lines 8–63why, one step back8</center>910### Performance tips1112For performance tips, see [Performance Tips](./performance.mdx#performance-tips).1314### Don't reassign the recipe argument1516Never reassign the `draft` argument (example: `draft = myCoolNewState`). Instead, either modify the `draft` or return a new state. See [Returning data from producers](./return.mdx).1718### Immer only supports unidirectional trees1920Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, there should be no circular references. There should be exactly one path from the root to any node of the tree.2122### Never explicitly return `undefined` from a producer2324It 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.2526### Don't mutate exotic objects2728Immer [does not support exotic objects](https://github.com/immerjs/immer/issues/504) such as window.location.2930### Classes should be made draftable or not mutated3132You will need to enable your own classes to work properly with Immer. For docs on the topic, check out the section on [working with complex objects](./complex-objects.md).3334### Only valid indices and length can be mutated on Arrays3536For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.3738### Data not originating from the state will never be drafted3940Note 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.4142```javascript43function onReceiveTodo(todo) {44 const nextTodos = produce(todos, draft => {45 draft.todos[todo.id] = todo46 // Note, because 'todo' is coming from external, and not from the 'draft',47 // it isn't draft so the following modification affects the original todo!48 draft.todos[todo.id].done = true4950 // The reason for this, is that it means that the behavior of the 2 lines above51 // is equivalent to code, making this whole process more consistent52 todo.done = true53 draft.todos[todo.id] = todo54 })55}56```5758### Immer patches are not necessarily optimal5960The set of patches generated by Immer should be correct, that is, applying them to an equal base object should result in the same end state. However Immer does not guarantee the generated set of patches will be optimal, that is, the minimum set of patches possible.6162### Always use the result of nested producers63Correct two typos. (#1072)Arthur Milchiorbefore adoption15a449a
line 64why, one step back64Nested `produce` calls are supported, but note that `produce` will _always_ produce a new state. So even when passing a draft to a nested produce, the changes made by the inner produce won't be visible in the draft of the outer produce; those changes will only be visible in the output that the inner `produce` returns. In other words, when using nested produce, you get a draft of a draft and the result of the inner produce should be merged back into the original draft (or returned). For example `produce(state, draft => { produce(draft.user, userDraft => { userDraft.name += "!" })})` won't work as the output of the inner produce isn't used. The correct way to use nested producers is:chore: Fix typo (#954)Marc Barbeaubefore adoptionba24aab
lines 65–89why, one step back6566```javascript67produce(state, draft => {68 draft.user = produce(draft.user, userDraft => {69 userDraft.name += "!"70 })71})72```7374### Drafts aren't referentially equal7576Draft objects in Immer are wrapped in `Proxy`, so you cannot use `==` or `===` to test equality between an original object and its equivalent draft (eg. when matching a specific element in an array). Instead, you can use the `original` helper:7778```javascript79const remove = produce((list, element) => {80 const index = list.indexOf(element) // this won't work!81 const index = original(list).indexOf(element) // do this instead82 if (index > -1) list.splice(index, 1)83})8485const values = [a, b, c]86remove(values, a)87```8889If possible, it's recommended to perform the comparison outside the `produce` function, or to use a unique identifier property like `.id` instead, to avoid needing to use `original`.feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0
lines 90–115why, one step back9091### Array Methods Plugin: Callbacks receive base values9293When using the [Array Methods Plugin](./array-methods.md) (`enableArrayMethods()`), callbacks for overridden methods like `filter`, `find`, `some`, `every`, and `slice` receive **base values** (not drafts). This is the core performance optimization - it avoids creating proxies for every element during iteration.9495```javascript96import {enableArrayMethods, produce} from "immer"97enableArrayMethods()9899produce(state, draft => {100 draft.items.filter(item => {101 // `item` is a base value here, NOT a draft102 // Reading works fine:103 return item.value > 10104105 // But direct mutation here won't be tracked:106 // item.value = 999 // ❌ Won't affect the draft!107 })108109 // Instead, use the returned result (which contains drafts):110 const filtered = draft.items.filter(item => item.value > 10)111 filtered[0].value = 999 // ✅ This works - filtered[0] is a draft112})113```114115This only applies to methods intercepted by the plugin. Methods like `map`, `forEach`, `reduce` are NOT overridden and work normally - their callbacks receive drafts.