JAVASCRIPT
Complex State Management using React's `useReducer` Hook
Explore how to manage complex component state in React applications more predictably and testably using the `useReducer` hook with a clear reducer function.
import React, { useReducer } from 'react';
// Reducer function
function 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 }; // payload could be new initial value
default:
throw new Error();
}
}
// Example Usage:
// function Counter() {
// const [state, dispatch] = useReducer(counterReducer, { count: 0 });
// return (
// <div>
// Count: {state.count}
// <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
// <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
// <button onClick={() => dispatch({ type: 'RESET', payload: 0 })}>Reset</button>
// </div>
// );
// }
How it works: The `useReducer` hook is an alternative to `useState` 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 sends 'actions' to the reducer, which then computes and returns the new state. This pattern makes state transitions more predictable and easier to test.