Nearby lessons

23 of 44

⚛️ ReactJS – useReducer Hook

📌 What is useReducer?

What is useReducer? Why do we use it?

useReducer is a React Hook used for state management. It is an alternative to useState(), and is usually preferred for handling complex state logic.

While useState is good for simple state updates, useReducer is better when your state logic involves multiple conditions or actions.

📌 What is useReducer?

  • It is a Hook for managing complex state logic
  • Alternative to useState
  • Takes a reducer function and an initial state
  • Returns [state, dispatch]

⚙️ Syntax of useReducer

The useReducer hook takes two arguments:

  • reducer → A function that handles state transitions
  • initialState → The starting value of the state

It returns an array with:

  1. state → Current state
  2. dispatch → Function to trigger actions

const [state, dispatch] = useReducer(reducer, initialState);

⚡ Execution Flow of useReducer

  1. Initial Setup: The useReducer hook is called with a reducer function and an initialState. It returns:
    • state → the current state value.
    • dispatch → a function used to send actions.
  2. Rendering: The component renders using the current state.
  3. Dispatch Action: When an event occurs (e.g., button click, form submit), dispatch(action) is called with a specific action object or value.
  4. Reducer Execution: The reducer function is executed with two arguments:
    • state → the current state.
    • action → the dispatched action.
    It processes the action and returns a new state.
  5. Re-render: React updates the component with the new state, causing a re-render with the latest data.

🧮 Example – Counter with useReducer

Below example demonstrates a simple counter app using useReducer.

  1. Initial Setup: The useReducer hook is called with a reducer function and an initialState. It returns an array with two values:
    • count → the current state value.
    • dispatch → a function to send actions to the reducer.
  2. Rendering: The component displays the initial count value (0).
  3. Dispatch Action: When a button is clicked, it calls dispatch("Increment") or dispatch("Decrement").
  4. Reducer Execution: The reducer function runs with the current state and the action:
    • If action = "Increment" → returns state + 1.
    • If action = "Decrement" → returns state - 1.
  5. Re-render: The new state is set as count, and React re-renders the component with the updated value.
React Playground
import React from 'react';
import './App.css';
import Counter from './Counter';

function App() {
  return (
    <>
      <h1>Learning useReducer</h1>
      <Counter/>
    </>
  );
}
export default App;

🔑 Key Points

  • Reducer function decides how the state changes
  • Dispatch is used to send an action
  • Each action type should be handled in the reducer
  • Good for managing complex state transitions

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - useCallback Hook