React Redux

Why we need Redux, if we can pass data using props ?
        Let say you want to pass data from some Grand Parent component to some grandchild component inside html DOM. You can easily do this by passing props from grandparents to parents, parents to children and children to grandchildren component. But the problem with is, that those components which do not need the data has access to it, which is not good for integrity purpose. That is why we use redux. 

These are some important and useful terms in react:
     Store: where the entire state of the application is stored 
     Reducer: function which modifies the state of the application based on some Action
     Action: these are some objects with consists of the events triggered in the application

Note: In redux state is an immutable object. It cannot be changed directly, to change the state the only way is to use Actions.


1. Store:
         Here we store the entire state of the application.
         import { configureStore } from "@reduxjs/toolkit"
         function reducerFunc(){}
         const store = configureStore({
                   reducer: reducerFunc
        })

Note: We can also use createStore() as well to create the store but problem with this method is that it is hard to maintain.

To know more about createStore and configureStore visit: https://redux.js.org/usage/configuring-your-store


2. Action:
         It is an Object which describes the event. It must contain a type property to tell about the type of the action.
Note: passing payload information in action is optional.
        Example:
                const update = (isAdmin) => {
                         return {
                                type:"UPDATE",
                                isAdmin
                         }
                }

3. Reducers:
       Reducers are the only way to modify the state in Redux. It contains the actual logic of state modification. Which means reducers are responsible for copying the current state, modify and return the new state.

      Syntax:
             const UpdateReducer =(state={}, action){
                 //Logic to modify the state
                 //return new state
             }

Note: You can use the createSlice or combineReducers to combine more than one reducers in Redux.

But in react-redux, there is a big change to make these operations more easier and readable. 
In this blog, we'll learn about React Redux other useful hooks:
      It also contains the same functionality as mentioned above, but with some changes like instead of using functions like mapStateToProps and mapDisatchToProps we now use useSelector() and useDispatch() hooks. So let's start by creating a simple counter application:

   First of all you need to install React-redux dependency as
          npm install @reduxjs/toolkit react-redux

Let's learn by creating a Counter Application:

1. Create a store: 
          Create a js file and paste the code-
             import {configureStore} from "@reduxjs/toolkit";
             import counterReducer from "./counterSlice"

             //pass the reducer function(s) to the store
             export default configureStore({
                      reducer:{
                            counter: counterReducer,
                      }
              })

2. Create one or more Reducers using createSlice:
           In createSlice you can pass 
               -name of the slice
              - initial state which you want to share between multiple component
              - reducers: one or more reducer functions

          Example:
            import {createSlice} from "@reduxjs/toolkit"

            export const counterSlice = createSlice({
                  name:"counter",
                  initialState:{
                      count:0,
                  },
                  reducers:{
                         increment:(state) =>{
                                 state.count+=1
                         },
                         decrement:(state)=>{
                                 state.count-=1
                         }
                  }
            })

           export const {decrement, increment} = counterSlice.actions;
           export default counterSlice.reducer;


Now wrap those components in which you want to share this state data inside Provider by passing store into it:

         const {Provider} from "react-redux"
         import {store} from './store'
         root.render(
                 <Provider store ={store}>
                        <Counter />
                 </Provider>
         )

         Counter.js
         import {decrement, increment } from "./store";
         import {useSelector, useDispatch} from 'react-redux';

        const Counter = () => {
              const dispatch = useDispatch();
              const count = useSelector(state => state.counter.count);

              Return(
                      <>
                           <p>Count: {count}</p>
                           <button onClick = {()=>dispatch(increment())}>Increment</button>
                            <button onClick = {()=>dispatch(decrement())}>Decrement</button>
                      </>
              );
        }

            Since Counter is provided under Provider that is why it is able to access the state, otherwise those components which are not inside the Provider will not have access to the state variable.

Continue Learning: useMemo and useCallback hook


            

Comments

Popular Posts