All VideosReact JS Tutorials

How to use useReducer Hook in React JS | Part 12 | React JS Tutorials in Hindi

In React.js, the useReducer hook is used for state management. It is an alternative to useState and is particularly useful when the state logic is complex and involves multiple sub-values or when the next state depends on the previous one. The useReducer hook is inspired by Redux and it follows the same principles of having a centralized state and actions to update that state.

Here’s a basic example of how to use useReducer in a React component:

import { useReducer } from "react";

export const UseReducerComponent = () => {
    const initialstate = 0
    const reducer = (count, action) =>{
        if(action.type === "Minus"){
            return count-1;
        }
        if(action.type === "Plus") {
            return count+1;
        }
    }
    const [count, dispatch] = useReducer(reducer, initialstate);
    
    return (
        <>
            <div className="text-format">
                <h1> My state {count}</h1>
                <div className="btn-wrapper">
                <button className="btn btn-blue" onClick={() => dispatch({type : "Minus"})}>Minus</button>
                <button className="btn btn-blue" onClick={() => dispatch({type : "Plus"})}>Plus</button>
                </div>
            </div>
        </>
    )
}

In this example:

  • reducer: This is a function that takes the current state and an action, and returns a new state based on the action. It’s a pure function with no side effects.
  • useReducer: This hook takes the reducer function and an initial state. It returns the current state and a dispatch function. The dispatch function is used to send actions to the reducer.
  • Inside the Counter component, we initialize the state using useReducer, passing in the reducer function and an initial state object { count: 0 }.
  • We have three buttons that dispatch different actions to the reducer when clicked: 'Plus' and 'Minus'.
  • The reducer function updates the state based on the action type, returning a new state object.
  • The component re-renders with the updated state, and the count is displayed accordingly.

This is a basic example, but useReducer can handle much more complex state logic by managing state transitions in a predictable way.

Leave a Reply

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

error: Content is protected !!