Introduction to Redux (Action, Reducers and Store)
Uses: It makes easier to manage state and data. As the complexity of our application increases. At the start, it is hard to understand but it really helps to build complex applications. In starting, it feels like a lot of work, but it is really helpful.
Before we dive into Redux we should know about some important principles of redux. There are three principles of Redux these are:
- Single source of truth: It helps to create universal apps. The state of the application is stored in one object tree called store. It means one app, one store.
- State is read-only (Immutability): It means that we don’t change the state object and its properties directly. Instead of this make a new object, recalculate the new application state and update it with our newly created object. And this is important because all the changes are happening in the same place so everything is needed to be done in strict order and one by one.
- Changes are made with pure functions (reducers): Reducers are pure functions that take previous state and action (discuss later) and return the new state.
Building Parts of redux:
Example: The easiest example we can take try is To-do. So we will create two action creators one for adding a task in to-do and for removing.
So, the above two functions are action creators. One is for adding a task and one for removing, and see both have a type which tells what is the purpose of actions creator and they will be used with reducers.
Reducers: As we already know, actions only tell what to do, but they don’t tell how to do, so reducers are the pure functions that take the current state and action and return the new state and tell the store how to do.
Let’s create a reducer for our TO-do.
So, In the above reducer, a function created with two arguments first is the current state and next is the action we want to perform, First initialize the current state empty array because at first task list is gonna be empty.
Then check the action type, different type of actions will have different functionality, In the above case if task is added, then it returns the array containing older list of task and with one new added, but the older state are not gonna mutate the older state we gonna return new one, this is needed to be kept in mind. Same for remove, if none of the above two then just return the list. Return the new state, Never mutate the older state.
For more complex apps use combineReducers() to combine them so that it can pass to store.
Store: The store is the object which holds the state of the application.
Functions associated with Store:
- createStore() – To create a store
- dispatch(action) -To change the state
- getState() – for getting current state of store.
Example: Let’s create a store for our TO-do.