useReducer manages complex state with a reducer function and dispatch actions. Define action types and how each changes state in a switch statement. Better than useState when multiple related values change together.
useReducer Hook
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment": return { count: state.count + 1 };
case "decrement": return { count: state.count - 1 };
case "reset": return { count: 0 };
default: throw new Error("Unknown action");
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>