Redux in React

Introduction

We have discuss core redux basics , now it's the time to explore redux in react at the basic level . Let's look at the redux step by step deeply in the sample project of react.
In this project , we will have the increment , decrement and show toggle actions which will manipulate the counter state and display the state accordingly.

First step , would be to create the store with the reducer function of the redux which will handle the change in the component and maintain the state across the react application.

In this example ,  we will declare the initial Values and set the counter = 0 and show = true whenever some action is dispatched ,  these default values  changes accordingly though the reducer function . If we don't specify the initial values that will bring result and error because the initial values are undefined or not declared as you are changing value which is not even defined, so it will obviously produce an error.


After declaring intialValues , it will pass in reducer function and assign it to state . As , we have discussed in earlier blogs it takes two parameters which is state and action . Through the action , we conditionally changes the state in the reducer function where we must return some value. It is basically a general function which return some value and not the reducer (the concept in javascript which reduces to some value) function of javascript.


Further , we pass the reducer function to the store and export the store to provide into the whole react application.


Second step , to provide the store in the main index.js file which is the root the react application. So , that the state can be used globally across the application . We will provide the store with the help of react-redux package which helps to used redux better in react.


Third and last step , to use the state in the application and dispatches the action in the handler function to change the state accordingly.

A - In the counter component , the useSelector and useDispatch will be imported from the react-redux . The method useSelector is used to get the particular state from the store and useDispatch function is used to dispatch the actions. You can look into the example where the type contains the string that conditionally triggered the actions whenever the user clicks the button.


Now, at the end we will use the state variables to show the counter value and put the handler function in the button element.


So, this is how we will use redux in react application and use the state across globally.
This is the code sandbox link ->Redux in react to help you get started with redux and can practice with the code.

Thanks for reading :)



Comments

Popular posts from this blog

Learn React Router v6 ( Part - 2)

Why use Typescript ?

What is Single Page Application Routing ?