The useReducer hook is used when your state logic becomes complex or when multiple values depend on each other. It works similar to reducers in Redux.
π― Why use useReducer?
β’ Manages complex state in a cleaner way
β’ Groups state updates with actions
β’ Easier to debug compared to multiple useState calls
π§ 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 (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</>
);
}
π Key points:
β’ useReducer(reducer, initialState) returns [state, dispatch]
β’ dispatch is used to trigger state changes
β’ Great for counters, forms, or any complex state logic
Top comments (0)