DEV Community

vidhya murali
vidhya murali

Posted on

useReducer Hook in React

The useReducer hook is a state management hook in React that provides an alternative to the useState hook. It is used when the state of a component is complex and requires more than one state variable.

It allows for custom state logic.

If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful.

Syntax:

const [state, dispatch] = useReducer(reducer, initialState, init)
Enter fullscreen mode Exit fullscreen mode
  • reducer: The reducer is a function responsible for defining how the state transitions from one state to another based on dispatched actions. It takes two arguments: the current state and the action being dispatched.

  • initialSate: initialState is the initial state value for the state managed by the reducer. It can be of any data type: object, array, number, string, etc., depending on the requirements of your application. It represents the initial state of your component before any actions are dispatched.

  • (optional) *init *: init is an optional initialization function that can be used to compute the initial state lazily. It is a function that returns the initial state value. If provided, it is called once during the initial render, and its return value is used as the initial state.

Example 1 :

import { useReducer, useState } from 'react'


function App() {

  let reducer=(state, action)=>{

    switch(action.type){
      case "increment" : return {...state,count:state.count+1}
      case "decrement" : return {...state,count:state.count>0? state.count-1 : state.count}
     }

  }
const[state,dispatch]=useReducer(reducer,{count:0})


  return (
    <>
     <h1>Counter App </h1>
     <h2>{state.count}</h2>
     <button  onClick={()=>dispatch({type:"increment"})}>inc</button>
     <button onClick={()=>dispatch({type:"decrement"})}>Dec</button>
    </>
  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

Example 2 :

import { useReducer } from 'react';
import { createRoot } from 'react-dom/client';

const initialScore = [
  {
    id: 1,
    score: 0,
    name: "John",
  },
  {
    id: 2,
    score: 0,
    name: "Sally",
  },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "INCREASE":
      return state.map((player) => {
        if (player.id === action.id) {
          return { ...player, score: player.score + 1 };
        } else {
          return player;
        }
      });
    default:
      return state;
  }
};

function Score() {
  const [score, dispatch] = useReducer(reducer, initialScore);

  const handleIncrease = (player) => {
    dispatch({ type: "INCREASE", id: player.id });
  };

  return (
    <>
      {score.map((player) => (
        <div key={player.id}>
          <label>
            <input
              type="button"
              onClick={() => handleIncrease(player)}
              value={player.name}
            />
            {player.score}
          </label>
        </div>
      ))}
    </>
  );
}

createRoot(document.getElementById('root')).render(
  <Score />
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)