Redux in React

In this article, we will learn how redux are work.

React Redux is the official React UI bindings layer for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update the state.

First, we have created a Reducer which is a pure function that takes an action and the previous state of the application and returns the new state.

const initialState = 10;

const changeTheNumber = (state = initialState, action) => {
    switch (action.type) {
        case "INCREMENT": return state + 1
        case "DECREMENT": return state - 1
        default: return state;
    }
}
export default changeTheNumber;

Then, we have to make a group(Combine) of all reducers.

import changeTheNumber from './upDown'
import { combineReducers } from 'redux'

const rootReducer = combineReducers({
    changeTheNumber: changeTheNumber
})
export default rootReducer;

Then, we have to create a store that is the common storage of the whole application.

import { createStore } from 'redux'
import rootReducer from './reducer/index'

const store = createStore(rootReducer);
export default store;

Then, run below command for dispatch the action.

npm i react-redux

Then, create the action which is dispatch action type.

export const incNumber = () =>{
    return{
        type:"INCREMENT"
    }
}
export const decNumber = () =>{
    return{
        type:"DECREMENT"
    }
}

Then,  dispatch action in app.js file. you can see below code.

import './App.css';
import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { incNumber, decNumber } from './action/index'

function App() {
  const myState = useSelector(state => state.changeTheNumber)
  const dispatch = useDispatch()
  return (
    <div style={{ textAlign: 'center' }}>
      <h3>Increment And Decrement Value</h3>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <button onClick={() => dispatch(decNumber())}>-</button>
        <h4 style={{ margin: "0px 10px" }}>{myState}</h4>
        <button onClick={() => dispatch(incNumber())}>+</button>
      </div>
    </div>
  );
}

export default App;

Here, we can use state value in all components. Redux store reduces the complexity of communication between components.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories