Skip to content
Myr

example-reducer.mdx

This file

Path

website/docs/example-reducer.mdx

79 lines · 2.3 KiB

Last changed by

docs: add `break` to `switch` block (#769)Greg Venechbefore adoptionb7fcf7f

History of this file

Take it

1---2id: example-reducer3title: Example Reducer4---56<center>7	<div8		data-ea-publisher="immerjs"9		data-ea-type="image"10		className="horizontal bordered"11	></div>12</center>13<details>14	<summary className="egghead-summary">15		egghead.io lesson 13: Using Immer in a (React) reducer16	</summary>17	<br />18	<div>19		<iframe20			width="760"21			height="427"22			scrolling="no"23			src="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer/embed"24		></iframe>25	</div>26	<a27		className="egghead-link"28		href="https://egghead.io/lessons/react-update-immutable-state-with-react-usereducer-through-immer"29	>30		Hosted on egghead.io31	</a>32</details>3334Here is a simple example of the difference that Immer could make in practice.3536```javascript37// Reducer with initial state38const INITIAL_STATE = {}39// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js40const byId = (state = INITIAL_STATE, action) => {41	switch (action.type) {42		case RECEIVE_PRODUCTS:43			return {44				...state,45				...action.products.reduce((obj, product) => {46					obj[product.id] = product47					return obj48				}, {})49			}50		default:51			return state52	}53}54```5556After using Immer, our reducer can be expressed as:5758```javascript59import produce from "immer"6061// Reducer with initial state62const INITIAL_STATE = {}6364const byId = produce((draft, action) => {65	switch (action.type) {66		case RECEIVE_PRODUCTS:67			action.products.forEach(product => {68				draft[product.id] = product69			})70			break71	}72}, INITIAL_STATE)73```7475Notice that it is not necessary to handle the default case, a producer that doesn't do anything will return the original state.7677Creating 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).7879_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 said draft. Don't do that. It removes the benefit of using Redux as a system where each reducer is testable as a pure function. Immer is best used when applied to small, individual pieces of logic._