JAVASCRIPT
Manage Complex State with React useReducer Hook
Effectively manage complex state logic in React components using the useReducer hook, providing a scalable and predictable alternative to useState for intricate state transitions.
import React, { useReducer } from 'react';
const initialState = { count: 0, showText: true };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
case 'decrement':
return { ...state, count: state.count - 1 };
case 'toggleText':
return { ...state, showText: !state.showText };
default:
throw new Error();
}
}
function CounterWithReducer() {
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: 'toggleText' })}>Toggle Text</button>
{state.showText && <p>This text can be toggled!</p>}
</div>
);
}
export default CounterWithReducer;
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 `dispatch` function sends 'actions' to the reducer, which then computes and returns the new state based on the action type, ensuring state updates are predictable and centralized.