JAVASCRIPT
Manage Complex State Transitions with useReducer
Learn how to use React's useReducer hook to manage complex state logic and transitions, providing a more structured and predictable alternative to useState for intricate components.
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 { count: initialState.count };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div className="counter-app">
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}
export default Counter;
How it works: The useReducer hook is ideal for managing complex state logic that involves multiple sub-values or when the next state depends on the previous one. It takes a reducer function and an initial state, returning the current state and a dispatch function. The reducer function defines how state transitions based on dispatched actions, centralizing state update logic and making it more predictable and testable than multiple useState calls.