JAVASCRIPT
Implement Complex State Logic with useReducer Hook
Learn how to manage complex state transitions and logic in React components using the useReducer hook, a powerful alternative to useState for intricate states.
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: action.payload };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset', payload: 0 })}>Reset</button>
</>
);
}
export default Counter;
How it works: The useReducer hook is used for managing more 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 'dispatch' function accepts an action object, which the reducer uses to compute the next state. This pattern is similar to Redux, making state updates predictable and testable.