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

--

--

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