useReducer

All about useReducer hook in React


useReducer lets you manage complex state logic using a reducer. Instead of calling setState directly, you dispatch actions to update state based on specific rules defined in your reducer. It’s similar to how state is managed in Redux but scoped to a single component.

LinkIconWhen to use

  • When the state logic is complex or depends on multiple sub-values.
  • When the next state depends on the previous one.
  • When setting a state depends on different actions.
  • When you want an alternative to useState for better maintainability in large components.

LinkIconUsage Example

import React, { 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: ${action.type}`);
  }
}
 
export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
 
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  );
}

LinkIconParameters

ParameterTypeDescription
reducerfunction(state, action) => newStateA pure function that takes the current state and an action, then returns the new state.
initialArganyThe initial value for the state, or an initial argument if using init.
init (optional)function(initialArg) => initialStateOptional initializer function to create the initial state lazily.

LinkIconReturns

ValueTypeDescription
stateanyThe current state value.
dispatchfunction(action) => voidA function to send actions to the reducer to update the state.

If you want, I can also make a "common patterns" section showing real-world useReducer patterns like async actions and multiple state slices, which would make the documentation more practical. Would you like me to add that?