A new approach to managing Redux actions

One action one file, with its reducer

import {
COUNTER_PLUS_ONE,
} from './constants';
export function counterPlusOne() {
return {
type: COUNTER_PLUS_ONE,
};
}
export function reducer(state, action) {
switch (action.type) {
case COUNTER_PLUS_ONE:
return {
...state,
count: state.count + 1,
};
default:
return state;
}
}

The wrapper reducer

import initialState from './initialState';
import { reducer as counterPlusOne } from './counterPlusOne';
import { reducer as counterMinusOne } from './counterMinusOne';
import { reducer as counterReset } from './counterReset';
const reducers = [
counterPlusOne,
counterMinusOne,
counterReset,
];
export default function reducer(state = initialState, action) {
let newState;
switch (action.type) {
// Put global reducers here
default:
newState = state;
break;
}
return reducers.reduce((s, r) => r(s, action), newState);
}

Handling cross-topic actions

  1. If chatting box is open, display it;
  2. If not, show a notification icon/message.

Benefits

  1. Easier to develop: no need to jump between files when creating actions.
  2. Easier to maintain: action files are now small and easy to be found just by file name.
  3. Easier to test: one test file corresponds to one action which also includes both action and reducer test.
  4. Easier to create tools: no need to parse code when creating a tool to generate Redux boilerplate code. A file template is enough.
  5. Easy to analyse: cross-topic actions could be easily found by static analysis.

Creating a code generator

import {
${ACTION_TYPE},
} from './constants';
export function ${CAMEL_ACTION_NAME}() {
return {
type: ${ACTION_TYPE},
};
}
export function reducer(state, action) {
switch (action.type) {
case ${ACTION_TYPE}:
return {
...state,
};
default:
return state;
}
}

Summary

--

--

--

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

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
Nate Wang

Nate Wang

More from Medium

Improve the performance of your React and React Native applications: Caching and managing your API…

Custom environments in a electron app (ElectronForge + webpack + react)

Global State Management with React Hooks

A Representation of how lot of hooks are able to solve react problems

React Component Lifecycle