What is the useReducer hook?
Answer
useReducer is an alternative to useState for managing complex state logic. It is inspired by Redux and follows the reducer pattern. Signature: const [state, dispatch] = useReducer(reducer, initialState);. The reducer function takes the current state and an action, and returns the new state: function reducer(state, action) { switch (action.type) { case "increment": return { ...state, count: state.count + 1 }; } }. Dispatch an action: dispatch({ type: "increment" }). When to use useReducer over useState: (1) Complex state with multiple sub-values where updates depend on each other. (2) Multiple state transitions that share logic. (3) State that involves many different "actions." (4) When the next state depends on the previous state in complex ways. Advantages: the reducer is a pure function — easy to test in isolation; all state transitions are explicit and traceable; makes it easier to add logging, undo/redo. useReducer pairs well with useContext to create a Redux-like global state without external libraries.