The useReducer
hook in React is an alternative to useState
for managing complex state logic in functional components. It's particularly useful when the state logic involves multiple sub-values or when the next state depends on the previous one. It's based on the reducer pattern, similar to how state management works in Redux.
Here's a basic example of how to use useReducer
:
import React, { useReducer } from 'react'; // Reducer function const 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() { // Initial state and dispatch function returned by useReducer const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); } export default Counter;
In this example:
reducer
function that specifies how state should be updated based on dispatched actions.Counter
component, we use useReducer
with the reducer
function and initial state { count: 0 }
.dispatch
to dispatch actions to the reducer, triggering state updates.useReducer
is particularly useful for managing complex state logic. You can have more complex state objects and handle multiple actions with the same reducer function.
useState
While useState
is simpler and often sufficient for managing local component state, useReducer
becomes more useful when:
useReducer
to centralize state management logic for better maintainability, especially in larger applications.useReducer
with Context API for managing global state across multiple components.