Lesson 6 / 25

Provider, useSelector and useDispatch

Connect React components with typed hooks.

Reading and writing from components

Wrap the app in React-Redux's <Provider store={store}>. useSelector(selector) subscribes a component to the store and re-renders it only when the selected value changes by strict reference equality (===). useDispatch() returns the store's dispatch. With TypeScript, create pre-typed hooks once so every component gets correct types; React-Redux 9 offers useSelector.withTypes<RootState>() and useDispatch.withTypes<AppDispatch>() for this (check the docs for your version; older code uses TypedUseSelectorHook).

Typed hooks and a component

hooks.ts and CartBadge.tsx.

// hooks.ts
import { useDispatch, useSelector } from 'react-redux';
import type { AppDispatch, RootState } from './store';

export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();

// CartBadge.tsx
export function CartBadge() {
  const count = useAppSelector((s) => s.cart.items.reduce((n, i) => n + i.qty, 0));
  const dispatch = useAppDispatch();
  return <button onClick={() => dispatch(cleared())}>Cart ({count})</button>;
}

// main.tsx
// <Provider store={store}><App /></Provider>

Select small values

Return the smallest value a component needs. A selector like (s) => s re-renders on every change, and one that builds a new array or object each time re-renders on every action.

Quick check: When does a component using useSelector re-render?

  • Only when the Provider remounts
  • On every dispatched action, always
  • Only when its props change
  • When the selected value changes by reference (===)
Answer

When the selected value changes by reference (===) — useSelector compares the previous and next selected values.