Mastering Effective Use of Reducers in React Redux
Reducers are part of Redux (which is a predictable state container for JS apps). Redux is used mostly for application state management in JS frameworks/libraries. Redux maintains the state of an entire application in a single immutable state tree (object) which cannot be changed directly. To change something, a new object must be created (using actions and reducers).
So what are reducers anyway?
Reducers are used in response to an action that is sent to the store (a single immutable store). Reducers specify how the application’s state changes while action only describes what happens. You can think of reducers like a state changer, Let’s take an example of simple application where you want to display a list of food dishes using React js with Redux. Now, this list will usually have 3 actions:
i) DISHES_LOADING: which indicates dishes are been loading.
ii) DISHES_FAILED: which indicates the application failed to fetch the dishes details.
iii) ADD_DISHES: This indicates adding new dishes to a list.
Fig.1. ActionTypes.jsx file
Fig.2. Dishes Reducer
Here you can see we don’t mutate the state, we simply create a return the new copies of the object. The default state returns the previous state.
But what if I had more than one reducer for my app?
You might need more than reducer for your app and you also want those reducers to have their results combined into a single object ( rather than different copies of the object ). Let’s take another reducer for comments:
Again, there will be three actions for comment:
i) ADD_COMMENT: This will indicate adding a new comment.
ii) COMMENT_FAILED: This will indicate the comment the user was trying to put failed.
iii) ADD_COMMENTS: This will add all the comments from the store.
Fig.3. Comment Reducer
Now, we need to combine these two reducers in order to create only a single new object when there is a state change. To do that use combineReducers() which generate a function that calls your reducers with the slices of the state selected according to their keys, and combines their results into a single object again.
Fig.4. Combining Reducer
This way you can easily create a reducer for your actions for the app you are creating. Always note down the actions of your component/components before you start coding, this way you need not worry about adding new actions later on.
Thank you for reading :)
Subscribe to my newsletter
Read articles from Rahul Bhatt directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by