Skip to content
ClapelloNotes by Barath
ReactCh 12 · 5/6
Core5 min readUpdated

React / 68

useSelector and useDispatch: a cart, end to end

TL;DR

Read the smallest piece of state you need with useSelector, send actions with useDispatch, and the cart updates everywhere at once.

Writing: useDispatch

src/components/MenuItem.jsx
import { useDispatch } from "react-redux";
import { addItem } from "../store/cartSlice";
 
export default function MenuItem({ dish }) {
  const dispatch = useDispatch();
 
  return (
    <li>
      {dish.name} · ₹{dish.price}
      <button onClick={() => dispatch(addItem(dish))}>Add {dish.name}</button>
    </li>
  );
}

addItem(dish) builds the action object; dispatch sends it to the store. MenuItem doesn't read any state, so it never re-renders because of the cart.

Reading: useSelector

src/components/Header.jsx
import { useSelector } from "react-redux";
import { Link } from "react-router";
 
export default function Header() {
  const count = useSelector((state) =>
    state.cart.items.reduce((total, item) => total + item.qty, 0)
  );
 
  return <Link to="/cart">Cart ({count})</Link>;
}

The function you pass is a selector: it gets the whole store state and returns the piece this component needs.

src/pages/CartPage.jsx
import { useDispatch, useSelector } from "react-redux";
import { clearCart, removeItem } from "../store/cartSlice";
 
export default function CartPage() {
  const items = useSelector((state) => state.cart.items);
  const dispatch = useDispatch();
 
  if (items.length === 0) return <p>Your cart is empty.</p>;
  return (
    <section>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name} × {item.qty}
            <button onClick={() => dispatch(removeItem(item.id))}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={() => dispatch(clearCart())}>Clear cart</button>
    </section>
  );
}

Click "Add" on the menu and the header count and the cart page both update. They never talk to each other: they both just read the store.

Select the smallest piece you need

After every dispatched action, useSelector re-runs your selector and compares the new result with the last one using ===. Different → re-render. Same → skip.

Big selector vs small selector

Try it

Header A

useSelector((state) => state)
Cart (0)renders: 1

Header B

useSelector((state) => state.cart.items.length)
Cart (0)renders: 1

store: cart has 0 items · user is Asha

Both headers show the same thing. Rename the user: Header A re-renders anyway, because it selected the whole store. Header B only re-renders when the count changes.

Don't

Select the whole store

const { cart } = useSelector((state) => state);

Every action makes a new root object, so this re-renders on any change, like a user rename. React-Redux even warns about it in development.

Do

Select exactly what you show

const items = useSelector((state) => state.cart.items);
const count = items.length;

Re-renders only when items itself changes.

Numbers, strings and booleans compare by value, so a selector returning items.length is cheap to keep stable. Arrays and objects compare by reference, which leads to the most common selector bug, below.

Reusable selectors

Write selectors next to the slice so every component reads state the same way. Redux Toolkit 2 lets a slice define them:

src/store/cartSlice.js (excerpt)
const cartSlice = createSlice({
  name: "cart",
  initialState: { items: [] },
  reducers: { /* addItem, removeItem, clearCart */ },
  selectors: {
    selectCartCount: (cart) => cart.items.reduce((n, item) => n + item.qty, 0),
  },
});
 
export const { selectCartCount } = cartSlice.selectors;
// in Header: const count = useSelector(selectCartCount);

Slice selectors receive the slice state (cart), and the exported versions take the root state, assuming the slice sits under its name key (cart) in the store.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.