What is useReducer in React?
useReducer
is a React hook that provides a more advanced way to manage state in functional components. It is especially useful for complex state logic where multiple state variables are interdependent or when state transitions require specific logic.
const [state, dispatch] = useReducer(reducer, initialState);
reducer
: A function that takes the current state and an action, then returns a new state.initialState
: The initial state value.dispatch
: A function to send actions to the reducer.
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("Unknown action type");
}
}
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>
</div>
);
}