DEV Community

Uma
Uma

Posted on • Updated on

How I implemented 'Redux' in my React project...

What I know about redux is this: It manages state. At the beginning of the curriculum, I thought Redux was only used in React but that was not the case. While it’s mostly used with React, it can be used with any other JavaScript framework or library like Agular, Vue, etc. Redux has three main parts: a store, actions, and reducers. The state of the application is kept in a store, and each component can access any piece of state that it needs from this store. We can create a store as shown below:

Alt Text

There is only one store in any Redux application. When using Redux with React, states will no longer need to be lifted up; thus, it makes it easier to trace which action causes any change.

Alt Text

As seen above, the component does not need to provide any state or method for its children components to share data among themselves. Everything is handled by Redux. To send data to the redux store we need “actions”. Actions are sent using the store.dispatch() method. An action is a plain JavaScript object and it must have a type property to indicate the type of action to be carried out. It can also. optionally, have a payload property that contains the information that should be worked on by the action. Let’s take a look at one of my action creators:

Alt Text

Here I am creating an action to log in the user and dispatching it to the reducer. Reducers are pure functions that take the current state of the application and an action and then return a new state. Here is an example of a simple reducer:

Alt Text

In a reducer depending on the action type, it returns a new state. We can have multiple reducers to handle complex applications. To do so we can use combineReducers() which combines all reducers in the application into a single index reducer. Every reducer is responsible for its own part of the application’s state, and the state parameter is different for every reducer. The combineReducers() utility makes the file structure much easier to maintain.

Here is what my combine reducer looks like:

Alt Text

Lastly, this reducer will be passed in createstore. There is much more to explain but here, I just tried to highlight the main features.

Thank you for reading. Happy coding...

Top comments (0)