State Management
React useSelector and useDispatch
useSelector reads a value from the Redux store and subscribes the component to it; useDispatch returns the store’s dispatch function so the component can send actions.
What is useSelector and useDispatch in React?
useSelector reads a value from the Redux store and subscribes the component to it; useDispatch returns the store’s dispatch function so the component can send actions.
useSelector and useDispatch example
// ✅ primitive result — re-renders only when the count changes
const count = useSelector(s => s.cart.items.length);
// ❌ new array each call — re-renders on every store change
const ids = useSelector(s => s.cart.items.map(i => i.id));
// ✅ memoised selector
const selectIds = createSelector(
s => s.cart.items,
items => items.map(i => i.id)
);
const ids = useSelector(selectIds);How this works
useSelector compares the previous and next result with strict equality. A selector that builds a new array or object fails that check every time, so it must be memoised with createSelector.
Key points to remember
- Prefer several small selectors over one that returns a big object.
- dispatch has a stable identity and never needs to be a dependency.
- createSelector from Reselect ships inside Redux Toolkit.
React useSelector and useDispatch— Interview Questions & FAQs
Why does my component re-render on every Redux action?+
The selector returns a new reference each time — typically a map, filter or object literal. Select primitives, or memoise the selector with createSelector.
