How To Start with Redux

ยท

3 min read

Hey folks, in this blog i would like to talk about what is redux. we will see what is redux & why redux. we will see how to start with redux and what are the inbuilt methods one can use to create their very own redux starter. so let's start.

what is Redux & why Redux

so, redux is basically used for managing state in react. So the problem with react is that ,it is unidirectional & the data flows from parent to child in lower direction of the DOM tree. But, what if one needs to pass the data directly to any child which is deep down in the tree, this is where the redux kicks in. Redux saves you from prop drilling and makes state management super easy. user can create its very own store , where the data can be stored for further use. This data can be directly accessed by any child in the DOM tree. we can also say that it is somewhat similar to contextAPI. or we can also say that, it serves as a centralized store for state that needs to be used across the entire app, with rules ensuring that the state can only be updated in a predictable fashion.

Now lets look at some important things which combines and makes the redux works properly.

1. ACTION

so Action is actually a plain javascript object, that have a type field init. Actions only tell what to do , but they don't tell how to do .lets say we have a task where we need to increment or decrement the quantity on clicking the button provided. so we can proceed as mentioned below see below for an example

return {
      type: "INCREMENT",
      payload: num
}
return {
      type: "DECREMENT",
      payload: num
}

2. REDUCER

so basically, Reducers are the functions which accepts two argument, one is the current State and other one is action , which we build earlier & then it returns us the new state result according to the passed condition. see below example

const initialStateValue=0;

const ReducerFunc=(state=initialStateValue,action)=>{
    switch(action.type){
           case "INCREMENT":
                       return {state+action.payload};
           case "DECREMENT":
                      return {state-action.payload};
           default:
                     return state;
           }
}

3. STORE

so now lets see what is Store . so , the work of store is to bring together the state, action & Reducer , which makes your app to work properly. Also its important to note that one can only have a single store in a Redux applcation. Also every store has a single root reducer function. see below for example

import {createStore} from "redux";
const store= createStore(rootReducers);

Points to remember

  • The global state of your application is stored as an object inside a single store

  • Also, the only way to change the state is to dispatch an action

So now just install all the dependencies in your app and get started with the redux. & thankyou for reading the blog. ๐Ÿ˜„

ย