Skip to content
Myr

Added examples from the Redux Update Patterns Page

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

authored by Michel Weststrate · committed by Michel Weststrate · parent 4e2e242 · Browse files · 1 file+63 added−0 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+63 added−0 removed

  • other:+63 added−0 removed

1 file+63 added−0 removed

modified:readme.md+63 added
168 unmodified lines
169```170171Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).172173---174175Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their immer counter part.176These examples are semantically equivalent and produce the exact same state.177178```javascript179// Plain reducer180function insertItem(array, action) {181 return [182 ...array.slice(0, action.index),183 action.item,184 ...array.slice(action.index)185 ]186}187188// With immer189function insertItem(array, action) {190 return immer(array, draft => {191 draft.splice(action.index, 0, action.item)192 })193}194195// Plain reducer196function removeItem(array, action) {197 return [198 ...array.slice(0, action.index),199 ...array.slice(action.index + 1)200 ];201}202203// With immer204function removeItem(array, action) {205 return immer(array, draft => {206 draft.splice(action.index, 1)207 })208}209210// Plain reducer211function updateObjectInArray(array, action) {212 return array.map( (item, index) => {213 if(index !== action.index) {214 // This isn't the item we care about - keep it as-is215 return item;216 }217218 // Otherwise, this is the one we want - return an updated value219 return {220 ...item,221 ...action.item222 };223 });224}225226// With immer227function updateObjectInArray(array, action) {228 return immer(array, draft => {229 draft[action.index] = { ...item, ...action.item}230 // Alternatively, since arbitrarily deep updates are supported:231 // Object.assign(draft[action.index], action.item)232 })233}234```235236## Performance237238Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.239This test takes 100.000 todo items, and updates 10.000 of them.
34 unmodified lines