Stop Using Giant Switch Statements in Your React Reducers

Let’s make our reducers cleaner and more flexible

Photo by Rich Smith on Unsplash

Let the Record Show…

A Better Way

const myMap = new Map([
[key1, value1],
[key2, value2],
]);

The Advantages

Scope

switch(something) {
case 'thing 1': {
const x = 'some const named x';
return x;
}
case 'thing 2': {
const x = 'some other const named x';
return x;
}
}

Portable Logic

const actionMap = new Map([
[actionTypes.BANNER_DISMISS, dismiss],
[actionTypes.BANNER_SHOW, show,
]);
switch(type) {
case actionTypes.BANNER_DISMISS:
return dismiss(state);
case actionTypes.BANNER_SHOW:
return show(state, payload);
}

Testability

Combining Maps

const actionMap = new Map([
...actionMap1,
...actionMap2,
...actionMap3,
...actionMap4,
]);

What have we learned?

Senior Front-end Engineer specializing in all things front-end software development.