useReducer

What is useReducer ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

useReducer is a React Hook that provides an alternative to useState for managing component state, particularly useful for more complex state logic. It is inspired by the Redux pattern.

useReducer() is a React Hook used to manage complex state logic in function components — especially when:

  1. State depends on previous state
  2. You have multiple related state values
  3. You want a cleaner alternative to useState() for bigger logic

Syntax

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

  1. state: current state value
  2. dispatch: function used to send actions
  3. reducerFunction: function that updates the state based on the action

Reducer Function

function reducer(state, action) {
 switch (action.type) {
   case "increment":
     return { count: state.count + 1 };
   case "decrement":
     return { count: state.count - 1 };
   default:
     return state;
 }
}

Example: Counter with useReducer()

import React, { useReducer } from 'react';

// 1. Reducer function
function reducer(state, action) {
 switch (action.type) {
   case "increment":
     return { count: state.count + 1 };
   case "decrement":
     return { count: state.count - 1 };
   default:
     return state;
 }
}

// 2. Component
function Counter() {
 const [state, dispatch] = useReducer(reducer, { count: 0 });

 return (
   <>
     <h2>Count: {state.count}</h2>
     <button onClick={() => dispatch({ type: "increment" })}>+1</button>
     <button onClick={() => dispatch({ type: "decrement" })}>-1</button>
   </>
 );
}

When to Use useReducer() vs useState()

Use useState() when...Use useReducer() when...
You have simple stateYou have complex or related state
You update one value at a timeYou need logic based on action types
One or two useState is enoughState updates depend on previous state

Summary

FeatureDescription
useReducer()Manages complex state with actions
dispatch()Triggers a state update using an action
reducer()Pure function to handle state updates
Alternative touseState()for complex state logic

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.