Hack Frontend Community

What is useReducer in React?

useReducer is a React hook that allows managing component state using a reducer — a function similar to reducer from Redux.
It's especially useful when:

  • state is complex (object, array),
  • many conditions/actions are needed to change state,
  • or when predictable update with clear logic is required.

Syntax

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer — function that accepts state and action, and returns new state.
  • initialState — initial state.
  • state — current state.
  • dispatch(action) — way to trigger state update.

Simple Example

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 };
    default:
      return state;
  }
}

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

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

How Does Reducer Work?

Reducer is a pure function that has no side effects and always returns new state based on current state and action.

(state, action) => newState

useReducer advantage:

The useReducer hook helps organize business logic separately from components, making them cleaner and easier to test.

Conclusion

  • useReducer is an alternative to useState, especially useful for complex state logic.
  • Allows centralized state management.
  • Makes component more predictable and testable.