JAVASCRIPT
Manage Complex State Logic with `useReducer` for a Counter
Explore `useReducer` to manage more intricate state logic than `useState`. This snippet provides a robust counter example with multiple actions (increment, decrement, reset, setValue).
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 initialState;
case 'setValue':
return { count: action.payload };
default:
throw new Error();
}
}
export function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
<button onClick={() => dispatch({ type: 'setValue', payload: 100 })}>Set to 100</button>
</div>
);
}
How it works: `useReducer` 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 based on the action type, ensuring predictable state transitions.