How to use React Redux in Functional Components

0

Hello guys, In this article, we will learn about React Redux. If you don't know about React, I already wrote an article on Creating First React Application .

You can't think of creating react application without Redux. You don't need to install Redux in a small project but if you need to share states between components that are not related to a parent-to-child concept time you can use React Redux.

There are many redux packages available on NPM, but currently, we are going to use react-redux, which is most easy to install and use.

If you use npm:

npm install react-redux

Or if you use Yarn:

yarn add react-redux

What is Redux and why do we need to install React redux?

React Redux is simply used as a global state management tool for React applications. This means that you have created a global state which can use for many of your application's components.

React uses a state where we save data for a moment. State work with the parent-to-child concept. But sometimes we need to get some of the states from other components at that time we need to use React redux to get state value. And it's a lightweight package.

Let's know about some common words in React redux.

Store: A Store is where the whole condition of your application records. It deals with the situation with the application and has a dispatch(action) work. It resembles a cerebrum liable for all moving parts in Redux.

Action: Activity is sent or dispatched from the view which are payloads that can be perused by Reducers. It is an unadulterated article made to store the data of the user's occasion. It incorporates data, for example, kind of activity, user auth status, user information, some other subtleties connected with project. its directions, and which state it plans to change.

Reducer: The Reducer reads the payloads that are sent with the action, and it updates the store.

How to use React Redux in Functional Components?

First of all, we will create another folder in the src folder, which will be named Reducers.

Inside that, we will create a file named index.js and write something like the below code inside it. Location project-name/src/Reducer/index.js

import * as actionTypes from "./types";
import { combineReducers } from "redux";

const initial_user_state={
    authStatus:false,
    userDetails:{}
}

const user_reducer=(state=initial_user_state,action)=>
{
    switch (action.type) {
        case actionTypes.SET_USER_DETAILS:
            return{
                ...state,
                userDetails: action.payload.userDetails,
            }
        case actionTypes.SET_AUTH_STATUS:
            return{
                ...state,
                authStatus: action.payload.authStatus,
            }
        default:return state
    }
}





const rootReducer = combineReducers({
     user:user_reducer
})


export default rootReducer

We will also create another file named types.js in the same Reducers folder where we define the types of the action, like in the below code. Location project-name/src/Reducer/types.js

/* 
        define and export all the action types here and use them in actions as well as in reducers

        ==> export const ACTION_TYPE = "ACTION_TYPE"


*/

export const SET_USER_DETAILS= "SET_USER_DETAILS";
export const SET_AUTH_STATUS= "SET_AUTH_STATUS";

Right now, we are talking about only two data, the first is user auth and the second is user data, both of which are very common.

How to create store and provide in react-redux?

One more thing left to do is create a store. For that, we import createStore from redux, import Provider from react-redux, and also import RootReducer from the Reducer folder. Wrap the app component in the provider tag with store props like the below snippet, which is already imported in the index.js file. Location project-name/src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './Components/App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import RootReducer from './Reducers'


let store = createStore(RootReducer)


ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

How to set data in react-redux?

We use functional hook useDispatch to set data in reducer. For that we import useDispatch from react-redux and we reformate it in const dispatch = useDispatch() after that function defined. And while sending data to redux we pass type and payload in dispatch.

import React,{useEffect} from 'react'
import { SET_AUTH_STATUS} from '../Reducers/types'
import { useDispatch } from 'react-redux';

export default function App() {
  const dispatch = useDispatch()

  useEffect(() => {
      dispatch({ type: SET_AUTH_STATUS, payload: { authStatus: true } })
  }, [])


  return (
    <>
    Send auth status true to reducer
    
    </>
  )
}

In the above code we have set the user auth status to for that we have also imported the SET_AUTH_STATUS type from Reducer's types.js folder.

How to get data from react-redux

We use functional hook useSelector to get data from reducer. For that we import useSelector from react-redux and make a const like the below snippents. From using the below snippetes we will get user's auth data if we have set.

import React,{useEffect} from 'react'
import '../App.css';
import {useSelector } from 'react-redux';


export default function App() {
  const userAuth = useSelector((state) => state.user.authStatus)

  useEffect(() => {
    console.log('getting user auth data', userAuth)

  }, [])



  return (
    <>
    Getting user Auth data from reducer using useSelector
    
    </>
  )
}

This is the easiest way to use reduer that I know. And I also use it in my daily life. I learnt this thing in my first internship when I started learning React. I also would like to know your insight on this if I missed something which should have covered here.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !