Sub topic 6
Connecting React: Provider, useSelector and useDispatch
This chapter assumes you can write a slice with createSlice, build a store with configureStore, and read basic React components with hooks. Here you connect that store to a component tree. React-Redux provides three tools for this: Provider, useSelector and useDispatch.
The three pieces
| Piece | Job |
|---|---|
| `Provider` | Puts the store into React context so any descendant can reach it. |
| `useSelector` | Reads a value from the state and re-renders the component when that value changes. |
| `useDispatch` | Returns the store's `dispatch` function so a component can send actions. |
A worked example
This example reuses the counter slice and the store from the earlier chapters. The slice exports the incremented and amountAdded action creators.
import { Provider, useSelector, useDispatch } from 'react-redux'
import { store } from './store'
import { incremented, amountAdded } from './counterSlice'
function Counter() {
const value = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<span>{value}</span>
<button onClick={() => dispatch(incremented())}>+1</button>
<button onClick={() => dispatch(amountAdded(5))}>+5</button>
</div>
)
}
export default function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
)
}Follow what happens when you click +5:
- The click handler calls
amountAdded(5), which builds the action{ type: 'counter/amountAdded', payload: 5 }. dispatchsends the action to the store, and the reducer produces the next state.- The store notifies its subscribers.
useSelectorruns your selector again. - The new result differs from the old one, so
Counterre-renders with the new value.
Provider
Wrap the part of the tree that needs the store, usually the whole app, in one Provider. Put it near the root, for example in the file that calls createRoot. A component outside the Provider that calls useSelector throws an error saying it could not find the store in context.
useSelector
The selector is a function that takes the whole state and returns the piece you need. Two rules matter in practice.
- Select the smallest value you need. The component re-renders when the selector's return value changes. Selecting
state.counter.valueis better than selecting all ofstate.counterand reading.valueafterward. - Compare by reference.
useSelectorchecks the result with===. A selector that builds a new array or object on every call, such asstate.todos.items.filter(...), returns a new reference each time. The component then re-renders after every dispatch. The next chapter shows howcreateSelectorsolves this.
useDispatch
useDispatch returns the same dispatch function for the life of the store. Call it with the result of an action creator, not with the action creator itself. dispatch(incremented) does nothing useful. dispatch(incremented()) is correct.
Components should describe what happened, such as incremented(), and leave the update logic to the reducer. Avoid computing the new state in the component and dispatching it.
Common errors
- "Could not find store in context": the component is not inside
Provider, or two copies ofreact-reduxare installed. - Re-renders on every dispatch: the selector returns a new object or array each call. Select a primitive, or memoize the result.
- Nothing happens on click: you passed the action creator without calling it.
Exercise
A component uses const items = useSelector((state) => state.todos.items.filter((t) => !t.completed)). It re-renders after every dispatched action, even unrelated ones. Why, and what is the fix?
Show answer
filter returns a new array on every call. useSelector compares results with ===, so it sees a changed value each time. Move the logic into a memoized selector built with createSelector, which returns the same array reference until state.todos.items changes.