Reducer And Store In Redux

Introduction

 
In the previous article, we have discussed the installation of Redux and how to get started with it. We have got a basic understanding of the core concepts of React. Now, in this article, we are going to discuss Reducer and Store in detail.
 

Reducer

 
Reducers are said to be "a pure function that accepts the current state of the application, evaluates the action, and returns a new state". Reducers specify how the application state changes in response to actions sent to the store.
 
It is based on the reduce() function of the JavaScript which returns a single value from multiple values passed to it after processed by a callback function.
 
(previousState,action) => newState
 
Let’s look at the demo for LoginComponent.
 
Here, I have created initialState for the component.
  1. const initialState = {  
  2.     username: "test",  
  3.     password: "test",  
  4.     loggedInStatus: ""  
  5. }  
Now, we are creating the reducer method.
  1. const reducer = (state = initialState, action) => {  
  2.     switch (action.type) {  
  3.         case LOGIN:  
  4.             return {  
  5.                 ...state,  
  6.                 username: action.username,  
  7.                 password: action.password,  
  8.                 loggedInStatus: callLoginApi(action.username, action.password)  
  9.             }  
  10.         default:  
  11.             return state  
  12.     }  
  13. }   
In the reducer function, CallLoginAPI method is called.
  1. function callLoginApi(username, password) {  
  2.     if (username === 'admin' && password === 'admin') {  
  3.         return "Login Success";  
  4.     } else {  
  5.         return 'Invalid email and password';  
  6.     }  
  7. }  
As Reducer functions are the pure functions which do not change the data in the object passed to these or perform any side effects in the application, providing the same object will always return the same result.
 
In the above code, we have used spread operator which states that it just needs to update a single property instead of a whole object.
 
While using reducer, it is required to remember two things.
  • State processing by reducer is immutable. This states that the property in the state is never changed directly. Therefore, the reducer function always returns a new state object.
  • Updating state after immutable data structure since we have spread operator makes sure that it will only update the desired property without modifying other state properties.
In Redux, there is a core concept of Store. A store is an immutable object tree in Redux. Redux has only one store for the entire application. Whenever a store is created in Redux, Reducer must be specified. Using this, we can access the state stored, update the store, and register or unregister listener via helper methods.
 
The main responsibilities of the store are -
  • It holds an application state.
  • It accesses the state by the getState() method.
  • It uses the dispatch() method to update the state; this method accepts action as a parameter.
  • The store also allows to register listeners to subscribe method, the subscribe method accepts a parameter named listener which can be executed any time redux store updates
  • It can also unregister the listeners subscribe via the function returned by subscribe(listener).
In Redux, we have Redux.createStore() method to create a store. For creating a store, we need to import the Redux package with importing of the createStore package.
 
Now, we will go into responsibilities one by one.
 
Import in JavaScript file.
  1. const redux = require('redux')  
As it holds application state, we have statement.
  1. const store = redux.createStore(reducer)   
Now, we know that the state can be returned using getState() so for that, it will display initial state of the store.
  1. console.log("Initial State",store.getState())  
See below.
 
Reducer And Store In Redux
 
Now, the next responsibility is to subscribe a mthod to subscribe store.
  1. store.subscribe(() => console.log('Updated state', store.getState()))  
Now, we can see how to dispatch a method. We will take action creator as parameter.
  1. store.dispatch(loggedIn("user""user"))  
  2. store.dispatch(loggedIn("testing""testing"))  
  3. store.dispatch(loggedIn("admin""admin"))  
Here, I have used dispatch method 3 times.
 
Now, the last responsibility is to unsubscribe the method subscribed previously.
  1. unsubscribe()  
Now, run the command in Terminal and check the output.
 
Reducer And Store In Redux
 
In the image above, you can see that 2 states have updated LoggedInStatus as Invalid email and Password while the third one is having Login success message. So, this way we can maintain the state and Reducer and perform some action on it.
 

Summary

 
In this article, we have learned about Reducer and Store in Redux. We have also learned how to implement it in Redux applications. Now, with this article, we have completed the core concepts of Redux. You can download the source code attached along with this article.
 
Now, in the next article, we will learn about functions provided by the Redux library along with its importance.