How to simplify the boilerplate for redux actions and reducers.

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 --saveNow 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.
