Simplify Redux reducers with immer

var a = [1, 2, 3];
var b = a;
a.push(4);
a === b; // true: reference equality is maintained
// ES5
var a = [1, 2, 3];
var b = [].concat(a, 4); // a new array is created, it is the result of concatenating a and 4
a === b; // false, something changed!
// ES6
const a = [1, 2, 3];
const b = [...a, 4];
a === b; // false, something changed!
const reducer = (state, action) => {
const { type, payload } = action;
switch (type) {
case 'add': {
const { value } = payload;
return [...state, value];
}
case 'delete': {
const { index } = payload;
return [
...state.slice(0, index),
...state.slice(index + 1)
];
}
case 'update': {
const { value, index } = payload;
return [
...state.slice(0, index),
value,
...state.slice(index + 1)
];
}
default: {
return state;
}
}
};
const reducer = produce((draft, action) => {
const { type, payload } = action;
switch (type) {
case 'add': {
const { value } = payload;
draft.push(value);
return draft;
}
case 'delete': {
const { index } = payload;
draft.splice(index, 1);
return draft;
}
case 'update': {
const { index, value } = payload;
draft[index] = value;
return draft;
}
default: {
return draft;
}
}
});
A simple React/Redux application using Immer

--

--

--

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Install WordPress on Vultr | Ultra Quickly Build WordPress

JavaScript : The one for all

Differences Between Promises and Async/Await in JavaScript

JavaScript30 — Day 20

Make your automated test browser always open in secondary screen on KDE Plasma/ openSUSE Tumbleweed

Making NodeJS Functions Sleep

#4 — Developing simple PropertyPanes App using SPFx

https://youtu.be/J1MsvciiTSU

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arnaud Dostes

Arnaud Dostes

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

More from Medium

Interact with object

Testing a React Component Library package locally, using Yarn and Craco

React Component Libraries

Lazy Loading with React Router

Unit test in React