JAVASCRIPT
Manage Complex State Logic with useReducer Hook
Learn how to use the `useReducer` hook in React to handle more intricate state logic, offering a predictable state container similar to Redux for local component state.
import React, { useReducer } from 'react';
// 1. Define initial state
const initialState = { count: 0, showText: true };
// 2. Define a reducer function
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
case 'decrement':
return { ...state, count: state.count - 1 };
case 'reset':
return initialState;
case 'toggleText':
return { ...state, showText: !state.showText };
default:
throw new Error();
}
}
function CounterWithReducer() {
// 3. Use useReducer hook
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>Count: {state.count}</h1>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
<hr />
<button onClick={() => dispatch({ type: 'toggleText' })}>Toggle Text</button>
{state.showText && <p>This text can be toggled!</p>}
</div>
);
}
export default CounterWithReducer;
How it works: The `useReducer` hook is an alternative to `useState` for managing more complex state logic that involves multiple sub-values or next state depending on the previous one. It takes a `reducer` function and an `initialState`. The `reducer` function receives the current `state` and an `action` object, returning the new state. The `dispatch` function is used to send actions, which then trigger the `reducer` to update the state. This pattern centralizes state updates, making them more predictable and testable, especially when state transitions are complex.