example-reducer.md
This file
Path
docs/example-reducer.md
57 lines · 2.1 KiB · Markdown
Last changed by
docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–7why, one step back1---2id: example-reducer3title: Example Reducer4---56<div id="codefund"><!-- fallback content --></div>7Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 8–11why, one step back8<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;">docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585
line 12why, one step back12 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer/embed" ></iframe>Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 13–16why, one step back13 </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>16Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 17–57why, one step back17Here 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._