example-reducer.md
This file
Path
docs/example-reducer.md
57 lines · 2.1 KiB · Markdown
Last changed by
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
History of this fileTake it
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 1–57why, one step back1---2id: example-reducer3title: Example Reducer4---56<div id="codefund"><!-- fallback content --></div>78<details>9 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 13: Using Immer in a (React) reducer</summary>10 <br>11 <div style="padding:5px;">12 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer/embed" ></iframe>13 </div>14 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer">Hosted on egghead.io</a>15</details>1617Here is a simple example of the difference that Immer could make in practice.1819```javascript20// Redux reducer21// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js22const byId = (state, action) => {23 switch (action.type) {24 case RECEIVE_PRODUCTS:25 return {26 ...state,27 ...action.products.reduce((obj, product) => {28 obj[product.id] = product29 return obj30 }, {})31 }32 default:33 return state34 }35}36```3738After using Immer, that simply becomes:3940```javascript41import produce from "immer"4243const byId = produce((draft, action) => {44 switch (action.type) {45 case RECEIVE_PRODUCTS:46 action.products.forEach(product => {47 draft[product.id] = product48 })49 }50})51```5253Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.5455Creating Redux reducer is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).5657_Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._