A cart whose changes all go through one reducer function. Dispatch actions and watch React run the reducer.
React · beginner · 8 min · 18 steps · free
import { useReducer } from 'react';
function cartReducer(cart, action) {
switch (action.type) {
case 'added':
return [...cart, action.item];
case 'cleared':
return [];
default:
throw new Error('Unknown action: ' + action.type);
}
}
export default function Cart() {
const [cart, dispatch] = useReducer(cartReducer, []);
return (
<div>
<p>{cart.length} items: {cart.join(', ')}</p>
<button onClick={() => dispatch({ type: 'added', item: 'Milk' })}>Add milk</button>
<button onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
</div>
);
}<Cart> for the first time: it calls the Cart function.useReducer stores the starting state, [], and gives back cart and dispatch.Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onClick handler.dispatch({ type: "added", item: "Milk" }) sends an action. The reducer has not run yet.useReducer returns the latest state: cart = ["Milk"].Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.onClick handler.dispatch({ type: 'cleared' }) sends an action. React will run the reducer with it on the next render.<Cart> again (render 3): it calls Cart once more, from the top.useReducer returns the latest state: cart = [].Cart returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Answer: In the reducer
Answer: No, return a new array
← useContext: Passing Data Deeply · Custom Hooks →