useReducer
All about useReducer hook in React
useReducer
lets you manage complex state logic using a reducer. Instead of calling setState
directly, you dispatch actions to update state based on specific rules defined in your reducer. It’s similar to how state is managed in Redux but scoped to a single component.
When to use
- When the state logic is complex or depends on multiple sub-values.
- When the next state depends on the previous one.
- When setting a state depends on different actions.
- When you want an alternative to
useState
for better maintainability in large components.
Usage Example
import React, { 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 };
case "reset":
return initialState;
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export default 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>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}
Parameters
Parameter | Type | Description |
---|---|---|
reducer | function(state, action) => newState | A pure function that takes the current state and an action, then returns the new state. |
initialArg | any | The initial value for the state, or an initial argument if using init . |
init (optional) | function(initialArg) => initialState | Optional initializer function to create the initial state lazily. |
Returns
Value | Type | Description |
---|---|---|
state | any | The current state value. |
dispatch | function(action) => void | A function to send actions to the reducer to update the state. |
If you want, I can also make a "common patterns" section showing real-world useReducer
patterns like async actions and multiple state slices, which would make the documentation more practical. Would you like me to add that?