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.
- const initialState = {
- username: "test",
- password: "test",
- loggedInStatus: ""
- }
Now, we are creating the reducer method.
- const reducer = (state = initialState, action) => {
- switch (action.type) {
- case LOGIN:
- return {
- ...state,
- username: action.username,
- password: action.password,
- loggedInStatus: callLoginApi(action.username, action.password)
- }
- default:
- return state
- }
- }
In the reducer function, CallLoginAPI method is called.
- function callLoginApi(username, password) {
- if (username === 'admin' && password === 'admin') {
- return "Login Success";
- } else {
- return 'Invalid email and password';
- }
- }
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.
- const redux = require('redux')
As it holds application state, we have statement.
- 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.
- console.log("Initial State",store.getState())
See below.
Now, the next responsibility is to subscribe a mthod to subscribe store.
- store.subscribe(() => console.log('Updated state', store.getState()))
Now, we can see how to dispatch a method. We will take action creator as parameter.
- store.dispatch(loggedIn("user", "user"))
- store.dispatch(loggedIn("testing", "testing"))
- store.dispatch(loggedIn("admin", "admin"))
Here, I have used dispatch method 3 times.
Now, the last responsibility is to unsubscribe the method subscribed previously.
Now, run the command in Terminal and check the output.
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.