example-reducer.md
This file
Path
docs/example-reducer.md
48 lines · 1.6 KiB · Markdown
Last changed by
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–48why, one step back1---2id: example-reducer3title: Example Reducer4---56<div id="codefund"><!-- fallback content --></div>78Here is a simple example of the difference that Immer could make in practice.910```javascript11// Redux reducer12// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js13const byId = (state, action) => {14 switch (action.type) {15 case RECEIVE_PRODUCTS:16 return {17 ...state,18 ...action.products.reduce((obj, product) => {19 obj[product.id] = product20 return obj21 }, {})22 }23 default:24 return state25 }26}27```2829After using Immer, that simply becomes:3031```javascript32import produce from "immer"3334const byId = produce((draft, action) => {35 switch (action.type) {36 case RECEIVE_PRODUCTS:37 action.products.forEach(product => {38 draft[product.id] = product39 })40 }41})42```4344Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.4546Creating 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).4748_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._