How to simplify the boilerplate for redux actions and reducers.

Sergei Gribovskii
Nov 1 · 2 min read

In the big React.js applications, the definitions of actions and reducers can become massive. To avoid mistypes for redux actions, we need to implement constants representing actions and use them in the reducers, redux-saga, components, and so on.

But is there a way to simplify the implementation and reduce costs for maintaining such boilerplate definitions. Well, now it is we can use npm package called ‘redux-contrib’.

So to start, we just need to install the package:

$ npm install redux-contrib --save

Now we can start implementing our actions:

import { createAction } from 'redux-contrib';export const createUserAction = createAction('CREATE_USER_ACTION', ['email', 'name']);

Once we have our actions implemented, we can define the reducer:

import { createReducer } from 'redux-contrib';
import { createUserAction } from 'actions';
const initialState = { user: undefined };const reducer = createReducer([
[
createUserAction,
(_, { email, name }) => ({ user: { email, name } }),
],
], initialState);
export default reducer;

Now you can use it in your components:

import { useDispatch } from 'react-redux';
import { createUserAction } from 'actions';
const SomeComponent = () => {
const dispatch = useDispatch();
const createUser = (email, name) => {
dispatch(createUserAction({ email, name }));
};
return(
...
);
}

Take a look at how more comfortable it becomes to implement actions and reducers. And here are the link to the package and source code.

Sergei Gribovskii

Written by

I’m a freelancer and entrepreneur changing people lives with technology.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade