Web Development React.js Subjective
Sep 28, 2025

What is the useReducer hook and when to use it over useState?

Detailed Explanation

useReducer manages complex state logic with multiple sub-values or when next state depends on previous state. Use it for complex state transitions.

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:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  
  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({type: "increment"})}>
        +
      </button>
    </div>
  );
}
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback