UseReducer Hook in React Js 2025

🔁 useReducer Hook in React JS 2025

The useReducer hook is an alternative to useState for managing complex state logic. It’s useful when you have multiple related state variables or when the next state depends on the previous one.

✨ Advantages of useReducer

  • Better for complex state logic involving multiple sub-values
  • Useful when the next state depends on the previous state
  • Helps organize code with state transitions via actions
  • Improves maintainability by separating state logic from UI logic

📦 Example: Simple Counter with useReducer


import { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return initialState;
    default:
      throw new Error('Unknown action type');
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    

Count: {state.count}

); }

📌 When to Use

  • When state logic becomes too complex for useState
  • When managing multiple pieces of state that depend on each other
  • For global or shared logic (in combination with context)