Skip to content
Myr

array-methods.md

This file

Path

website/docs/array-methods.md

277 lines · 9.7 KiB · Markdown

Last changed by

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

History of this file

Take it

feat: Override array methods to avoid proxy creation while iterating and updating (#1184)Mark Eriksonbefore adoptiond38a9d0

lines 1–277why, one step back
1---
2id: array-methods3title: Array Methods Plugin4---56<center>7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>8</center>910## Overview1112The Array Methods Plugin (`enableArrayMethods()`) optimizes array operations within Immer producers by avoiding unnecessary Proxy creation during iteration. This provides significant performance improvements for array-heavy operations.1314**Why does this matter?** Without the plugin, every array element access during iteration (e.g., in `filter`, `find`, `slice`) creates a Proxy object. For a 1000-element array, this means 1000+ proxy trap invocations just to iterate. With the plugin enabled, callbacks receive base (non-proxied) values, and proxies are only created as needed for mutation tracking.1516## Installation1718Enable the plugin once at your application's entry point:1920```javascript21import {enableArrayMethods} from "immer"2223enableArrayMethods()24```2526This adds approximately **2KB** to your bundle size.2728## Mutating Methods2930These methods modify the array in-place and operate directly on the draft's internal copy without creating per-element proxies:3132| Method | Returns | Description |33| ----------- | ---------------- | ------------------------------------- |34| `push()` | New length | Adds elements to the end |35| `pop()` | Removed element | Removes and returns the last element |36| `shift()` | Removed element | Removes and returns the first element |37| `unshift()` | New length | Adds elements to the beginning |38| `splice()` | Removed elements | Adds/removes elements at any position |39| `sort()` | The draft array | Sorts elements in place |40| `reverse()` | The draft array | Reverses the array in place |4142```javascript43import {produce, enableArrayMethods} from "immer"4445enableArrayMethods()4647const base = {items: [3, 1, 4, 1, 5]}4849const result = produce(base, draft => {50 draft.items.push(9) // Adds 9 to end51 draft.items.sort() // Sorts: [1, 1, 3, 4, 5, 9]52 draft.items.reverse() // Reverses: [9, 5, 4, 3, 1, 1]53})54```5556## Non-Mutating Methods5758Non-mutating methods are categorized based on what they return:5960### Subset Operations (Return Drafts)6162These methods select items that exist in the original array and **create draft proxies** for the returned items. The callbacks receive **base values** (the optimization), but the **returned array** contains newly created draft proxies that point back to the original positions. **Mutations to returned items WILL affect the draft state.**6364| Method | Returns | Drafts? |65| ------------ | ---------------------------------- | ------- |66| `filter()` | Array of matching items | ✅ Yes |67| `slice()` | Array of items in range | ✅ Yes |68| `find()` | First matching item or `undefined` | ✅ Yes |69| `findLast()` | Last matching item or `undefined` | ✅ Yes |7071```javascript72const base = {73 items: [74 {id: 1, value: 10},75 {id: 2, value: 20},76 {id: 3, value: 30}77 ]78}7980const result = produce(base, draft => {81 // filter returns drafts - mutations track back to original82 const filtered = draft.items.filter(item => item.value > 15)83 filtered[0].value = 999 // This WILL affect draft.items[1]8485 // find returns a draft - mutations track back86 const found = draft.items.find(item => item.id === 3)87 if (found) {88 found.value = 888 // This WILL affect draft.items[2]89 }9091 // slice returns drafts92 const sliced = draft.items.slice(0, 2)93 sliced[0].value = 777 // This WILL affect draft.items[0]94})9596console.log(result.items[0].value) // 77797console.log(result.items[1].value) // 99998console.log(result.items[2].value) // 88899```100101### Transform Operations (Return Base Values)102103These methods create **new arrays** that may include external items or restructured data. They return **base values**, NOT drafts. **Mutations to returned items will NOT track back to the draft state.**104105| Method | Returns | Drafts? |106| ---------- | ------------------- | ------- |107| `concat()` | New combined array | ❌ No |108| `flat()` | New flattened array | ❌ No |109110```javascript111const base = {items: [{id: 1, value: 10}]}112113const result = produce(base, draft => {114 // concat returns base values - mutations DON'T track115 const concatenated = draft.items.concat([{id: 2, value: 20}])116 concatenated[0].value = 999 // This will NOT affect draft.items[0]117118 // To actually use concat results, assign them:119 draft.items = draft.items.concat([{id: 2, value: 20}])120})121122// Original unchanged because concat result wasn't assigned123console.log(result.items[0].value) // 10 (unchanged)124```125126**Why the distinction?**127128- **Subset operations** (`filter`, `slice`, `find`) select items that exist in the original array. Returning drafts allows mutations to propagate back to the source.129- **Transform operations** (`concat`, `flat`) create new data structures that may include external items or restructured data, making draft tracking impractical.130131### Primitive-Returning Methods132133These methods return primitive values (numbers, booleans, strings). No tracking issues since primitives aren't draftable:134135| Method | Returns |136| ------------------ | -------------------- |137| `indexOf()` | Number (index or -1) |138| `lastIndexOf()` | Number (index or -1) |139| `includes()` | Boolean |140| `some()` | Boolean |141| `every()` | Boolean |142| `findIndex()` | Number (index or -1) |143| `findLastIndex()` | Number (index or -1) |144| `join()` | String |145| `toString()` | String |146| `toLocaleString()` | String |147148```javascript149const base = {150 items: [151 {id: 1, active: true},152 {id: 2, active: false}153 ]154}155156const result = produce(base, draft => {157 const index = draft.items.findIndex(item => item.id === 2)158 const hasActive = draft.items.some(item => item.active)159 const allActive = draft.items.every(item => item.active)160161 console.log(index) // 1162 console.log(hasActive) // true163 console.log(allActive) // false164})165```166167## Methods NOT Overridden168169The following methods are **not** intercepted by the plugin and work through standard Proxy behavior. Callbacks receive drafts, and mutations track normally:170171| Method | Description |172| --------------- | --------------------------------- |173| `map()` | Transform each element |174| `flatMap()` | Map then flatten |175| `forEach()` | Execute callback for each element |176| `reduce()` | Reduce to single value |177| `reduceRight()` | Reduce from right to left |178179```javascript180const base = {181 items: [182 {id: 1, value: 10, nested: {count: 0}},183 {id: 2, value: 20, nested: {count: 0}}184 ]185}186187const result = produce(base, draft => {188 // forEach receives drafts - mutations work normally189 draft.items.forEach(item => {190 item.value *= 2191 })192193 // map is NOT overridden - callbacks receive drafts194 // The returned array items are also drafts (extracted from draft.items)195 const mapped = draft.items.map(item => item.nested)196 // Mutations to the result array propagate back197 mapped[0].count = 999 // ✅ This affects draft.items[0].nested.count198})199200console.log(result.items[0].nested.count) // 999201```202203## Callback Behavior204205For overridden methods, callbacks receive **base values** (not drafts). This is the core optimization - it avoids creating proxies for every element during iteration.206207```javascript208const base = {209 items: [210 {id: 1, value: 10},211 {id: 2, value: 20}212 ]213}214215produce(base, draft => {216 draft.items.filter(item => {217 // `item` is a base value here, NOT a draft218 // Reading properties works fine219 return item.value > 15220221 // But direct mutation here won't be tracked:222 // item.value = 999 // ❌ Won't affect draft223 })224225 // Instead, use the returned draft:226 const filtered = draft.items.filter(item => item.value > 15)227 filtered[0].value = 999 // ✅ This works because filtered[0] is a draft228})229```230231## Method Return Behavior Summary232233| Category | Methods | Returns | Mutations Track? |234| --- | --- | --- | --- |235| **Subset** | `filter`, `slice`, `find`, `findLast` | Draft proxies | ✅ Yes |236| **Transform** | `concat`, `flat` | Base values | ❌ No |237| **Primitive** | `indexOf`, `includes`, `some`, `every`, `findIndex`, `findLastIndex`, `lastIndexOf`, `join`, `toString`, `toLocaleString` | Primitives | N/A |238| **Mutating** | `push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse` | Various | ✅ Yes (modifies draft) |239| **Not Overridden** | `map`, `flatMap`, `forEach`, `reduce`, `reduceRight` | Standard behavior | ✅ Yes (callbacks get drafts) |240241## When to Use242243Enable the Array Methods Plugin when:244245- Your application has significant array iteration within producers246- You frequently use methods like `filter`, `find`, `some`, `every` on large arrays247- Performance profiling shows array operations as a bottleneck248249The plugin is most beneficial for:250251- Large arrays (100+ elements)252- Frequent producer calls with array operations253- Read-heavy operations (filtering, searching) where most elements aren't modified254255## Performance Benefit256257**Without the plugin:**258259- Every array element access during iteration creates a Proxy260- A `filter()` on 1000 elements = 1000+ proxy creations261262**With the plugin:**263264- Callbacks receive base values directly265- Proxies only created for the specific elements you actually mutate, or that match filtering predicates266267```javascript268// Without plugin: ~3000+ proxy trap invocations269// With plugin: ~10-20 proxy trap invocations270const result = produce(largeState, draft => {271 const filtered = draft.items.filter(x => x.value > threshold)272 // Only items you mutate get proxied273 filtered.forEach(item => {274 item.processed = true275 })276})277```