JAVASCRIPT
Manage Complex Component State with `useReducer` Hook
Learn how to effectively manage complex state logic in React components using the `useReducer` hook, ideal for intricate state transitions and predictable state updates.
import React, { useReducer } from 'react';
// Reducer function
const counterReducer = (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:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
<button onClick={() => dispatch({ type: 'RESET', payload: 0 })}>Reset</button>
</div>
);
}
export default Counter;
How it works: The `useReducer` hook is an alternative to `useState` for 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 sends 'actions' to the reducer, which then computes and returns the new state based on the action type, making state updates more predictable and testable.