DEV Community

Cover image for Minimize redux boilerplate with these 7 lines of code!
kapeel kokane
kapeel kokane

Posted on

Minimize redux boilerplate with these 7 lines of code!

The Setup

Have you ever worked with applications where you use redux for state management? I am sure you have. It's beautiful how the framework lets us use the one way state flow by dispatching actions, making use of pure functions and immutability to provide a nearly perfect state management option for small/medium apps.

But there is an issue I have with redux: the boilerplate that comes associated with it.

The Issue

Although redux is not opinionated, there is generally a standard way of doing stuff: write action creators, use functions like 'mapStateToProps', 'mapDispatchToProps', use the 'connect' function, use thunk for async actions etc.

One of those "standards" is the way in which one performs a simple request, success/failure operation on an API.

Here's the drill:

  1. Create a 'REQUEST' action and dispatch it.
  2. Make the network request.
  3. On success, dispatch the 'SUCCESS' action with the payload.
  4. On failure, dispatch the 'FAILURE' action with the error.

This is so common that react official documentation has an entire article on how to minimize boilerplate for this pattern:
https://redux.js.org/recipes/reducing-boilerplate

The actual Issue

But what if your problem statement does not fit into the straightjacket of this pattern mentioned above and you are unable to use any of the solutions mentioned in the link above. Same was the case with my problem statement and I thought to myself how I can still reduce my boilerplate.

Then, I Stumbled upon my constants.js file that held my actions. It looked something like this:
React actions mess

and whenever I wanted to import actions, I did this:
Use actions like this

Or worse still, in some cases the constants were imported like so:
Other usage of constants

A better way

Here's how the constants file can be made smaller, concise and easier to read.
First, write a util function and call it something like:
Generate actions helper

Then, the constants.js file can look something like this:
Modified constants file

And the constants can then be used in this manner:
Constants usage

or like this:
alternate constants usage

So, in this way, we can minimize at least the constants boilerplate that causes files to bloat up and makes the code less understandable.

Top comments (0)