Sub topic 6
Connecting React: Provider, useSelector and useDispatch
This chapter assumes you can write function components with useState and useEffect. It also assumes you have a store from configureStore and at least one slice from createSlice. The chapter covers how React-Redux connects that store to your components, how re-renders are decided, and the mistakes that cause unneeded renders or stale reads.
The role of React-Redux
Redux Toolkit and the store know nothing about React. The react-redux package is the binding layer. It gives you three pieces:
Providerputs the store into React context.useSelectorreads a value from the store and subscribes the component to changes.useDispatchreturns the store'sdispatchfunction.
Install it next to Redux Toolkit:
npm install @reduxjs/toolkit react-reduxProviding the store
Provider takes a store prop and makes it available to every component below it. Place it once, near the root of the app.
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>
)
}The context holds the store object itself, not the state. The store object never changes, so Provider does not cause re-renders when state changes. Components re-render because of their own subscriptions, set up by useSelector.
Reading state with useSelector
useSelector takes a function called a selector. The selector receives the whole Redux state and returns the piece the component needs.
const value = useSelector((state) => state.counter.value)Internally, the hook does the following:
- It runs your selector during render and returns the result.
- It subscribes to the store.
- After every dispatched action, it runs the selector again with the new state.
- It compares the new result with the previous one using strict reference equality (
===). - It forces a re-render only if the two differ.
Step 4 explains most useSelector problems. A selector that returns a number or string is compared by value, because primitives with the same value are ===. A selector that returns an object or array is compared by reference.
Select the smallest value you need
A component re-renders only when its selected value changes. Selecting a narrow value limits re-renders.
// Re-renders whenever anything in the user object changes
const user = useSelector((state) => state.user)
// Re-renders only when the name changes
const name = useSelector((state) => state.user.name)Redux Toolkit's Immer-based reducers keep unchanged branches of the state at the same reference. If state.user.age changes, state.user.name is still the same string, and state.todos is still the same array. A component that selects only unchanged data is not re-rendered.
The new-reference trap
A selector that builds a new object or array on every call returns a different reference each time. The comparison always fails, so the component re-renders after every dispatched action, even for unrelated ones.
// Bad: filter() returns a new array on every call
const doneTodos = useSelector((state) =>
state.todos.items.filter((t) => t.completed)
)React-Redux 8.1 and later run a development-mode check and warn you when a selector returns a different result for the same input. Treat that warning as a real bug.
You have three ways to fix it:
- Select the stored data and derive the result in the component body, if the cost is small.
- Use
createSelectorto memoize the derivation, as the next chapter explains. - Select several primitives with separate
useSelectorcalls.
You can also pass shallowEqual as a second argument, which compares the top-level fields of the result:
import { useSelector, shallowEqual } from 'react-redux'
const { name, email } = useSelector(
(state) => ({ name: state.user.name, email: state.user.email }),
shallowEqual
)This works, but separate calls or a memoized selector are usually clearer.
Selectors can use props
A selector defined inline can close over props or local variables. It is recreated each render, which is fine.
function TodoItem({ id }) {
const todo = useSelector((state) =>
state.todos.items.find((t) => t.id === id)
)
return <li>{todo.title}</li>
}If find returns an item that Immer has not touched, the reference is stable and the component does not re-render for edits to other todos.
Sending actions with useDispatch
useDispatch returns the store's dispatch. You call it with an action object. Action creators produced by createSlice build those objects for you.
const dispatch = useDispatch()
dispatch(amountAdded(5))
// dispatches { type: 'counter/amountAdded', payload: 5 }The dispatch function has a stable identity for the life of the store. You can put it in a useEffect dependency array without causing the effect to re-run.
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { incremented } from './counterSlice'
function Ticker() {
const dispatch = useDispatch()
useEffect(() => {
const id = setInterval(() => dispatch(incremented()), 1000)
return () => clearInterval(id)
}, [dispatch])
return null
}Dispatch an object of intent, not a setter
Components should describe what happened (todoAdded, checkoutSubmitted) and let reducers decide how state changes. Avoid passing computed new state values through the payload when the reducer can compute them from the current state. This keeps logic testable and in one place.
Where components should read and dispatch
A common design question is how many components should talk to the store. The usual guidance is to let components read the data they need directly, instead of reading everything in a parent and passing it down through props.
- A container-like component near the top selects only what it needs.
- Deeper components that need store data call
useSelectorthemselves. - Reusable presentational components that should not know about Redux take values and callbacks as props.
Selecting in the leaf component keeps parent re-renders from cascading. If a parent selects a large object and passes pieces down, the parent re-renders on every change to that object and so do its children, unless they are memoized.
Batching and the render cycle
React-Redux relies on React's automatic batching. When several actions are dispatched in one event handler, React groups the resulting updates and renders once.
function reset() {
dispatch(filterCleared())
dispatch(pageReset())
dispatch(selectionCleared())
}Each dispatch runs the reducers and notifies subscribers, so the store state does change three times. React batches the re-renders, so the component renders once with the final state. If you need several state changes to count as a single event in DevTools, dispatch one action that several slices respond to, a pattern covered in the extraReducers chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `could not find react-redux context value` | A component using hooks is rendered outside `Provider` | Wrap the app (or the test render) in `Provider` |
| Warning: selector returned a different result | Selector builds a new array or object each call | Use `createSelector`, or select primitives |
| Component re-renders on every action | Selecting a whole slice or a new reference | Select a narrower value |
| `Cannot read properties of undefined` | The selector path does not match the state shape | Check the key names given to `configureStore` |
| Stale value inside a callback | Value was read once and captured by an old closure | Select inside the component and add it to dependencies, or read state inside a thunk |
| Action dispatched but UI does not change | Reducer mutated state outside Immer, or returned `undefined` | Review the slice; see the Immer chapter |
The path error deserves a note. In the slice example, the store was configured with reducer: { counter: counterSlice.reducer }. The key counter is why the selector reads state.counter.value. Renaming the key in the store breaks every selector that reads it.
Do not copy store state into local state
A frequent mistake is to read a value from the store and copy it into useState.
// Avoid: the copy goes stale when the store changes
const value = useSelector((state) => state.counter.value)
const [local, setLocal] = useState(value)The initial value is read once, and later store updates do not reach local. Keep one source of truth. Use the store value directly, or keep the value out of Redux entirely if it only matters to this component, such as the text in a form field being typed.
Summary of the data flow
When a user clicks a button, the handler calls dispatch with an action. The store passes the action to the root reducer, which produces new state. The store notifies subscribers. Each useSelector re-runs its selector and compares the result by reference. Only components whose result changed re-render. This keeps data flowing in one direction, from the store down to the UI.
Exercise
A component uses const items = useSelector((state) => state.todos.items.map((t) => t.title)). It re-renders after every dispatched action, even actions that only change state.user. Why does this happen, and name two ways to fix it.
Show answer
map returns a new array on every call, so useSelector sees a different reference after each action and forces a re-render. Fix it by memoizing the derivation with createSelector so the same array is returned while state.todos.items is unchanged. You can also select state.todos.items and call map in the component body, or pass shallowEqual as the second argument so the arrays are compared item by item.
Exercise
Why does putting dispatch in a useEffect dependency array not cause the effect to run again on each render?
Show answer
The store's dispatch function keeps the same identity for the life of the store, so the dependency never changes between renders.