useReducer
RE · Additional Hookssyntax
const [state, dispatch] = useReducer(reducer, initialState);
// reducer: (state, action) => newStateexample
import { useReducer } from 'react';
function cartReducer(state, action) {
switch (action.type) {
case 'ADD_ITEM':
return { ...state, items: [...state.items, action.payload] };
case 'REMOVE_ITEM':
return {
...state,
items: state.items.filter(i => i.id !== action.payload),
};
case 'CLEAR':
return { ...state, items: [] };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function ShoppingCart() {
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
return (
<div>
<p>{cart.items.length} items</p>
<button onClick={() =>
dispatch({ type: 'ADD_ITEM', payload: { id: 1, name: 'Notebook' } })
}>
Add Notebook
</button>
<button onClick={() => dispatch({ type: 'CLEAR' })}>
Clear Cart
</button>
</div>
);
}Note Prefer useReducer over useState when you have complex state logic with multiple sub-values, or when the next state depends on the previous state in varied ways. The reducer function must be pure -- no side effects.