Real World Example

Real World: Product page: size and quantity

On a clothing site the selected size, quantity and wishlist heart are each a piece of state.

function ProductOptions({ stock }) {
  const [size, setSize] = useState('M');
  const [qty, setQty] = useState(1);
  const [wish, setWish] = useState(false);
  return (
    <>
      {['S', 'M', 'L', 'XL'].map((s) => (
        <button key={s} className={s === size ? 'selected' : ''} onClick={() => setSize(s)}>{s}</button>
      ))}
      <button onClick={() => setQty((q) => Math.max(1, q - 1))}>-</button> {qty}
      <button onClick={() => setQty((q) => Math.min(stock, q + 1))}>+</button>
      <button onClick={() => setWish(!wish)}>{wish ? '❤' : '♡'}</button>
    </>
  );
}