useReducer
The useReducer
hook in React is used for state management and is an alternative to useState
. It's particularly useful when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer
is also handy when you want to optimize performance for components that trigger deep updates because you can pass down dispatch instead of callbacks.
Syntax
The useReducer
hook takes two required arguments and one optional argument:
- Reducer function: A function that takes the current state and an action, and returns a new state.
- Initial state: The initial state of the component.
- Initializer function (optional): A function that computes the initial state.
const [state, dispatch] = useReducer(reducer, initialState, initializer);
Reducer Function
The reducer function takes the current state and an action as arguments and returns a new state. The action object typically has a type
field that describes the type of action being performed.
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();
}
}
Example
Here's a simple example that uses useReducer
to implement a counter:
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 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</>
);
}
In this example, the useReducer
hook manages the state of the Counter
component. The dispatch
function is used to dispatch actions that are handled by the reducer
function to update the state.
When to Use useReducer
- When you have complex state logic that involves multiple sub-values.
- When the next state depends on the previous one.
- When you want to pass down the
dispatch
function deep into the component tree instead of callbacks.
useReducer
offers more control over state updates and makes it easier to understand and manage complex state logic.