Select a flat object
A selector returns a newly constructed object containing primitive fields such as count and status.
Redux Toolkit · Function
shallowEqual is a React-Redux comparison function for useSelector. It compares top-level fields of selector results, making it useful when a selector returns a new flat object whose field values are unchanged.
shallowEqual compares the fields of two values rather than requiring the returned object itself to have the same reference. Supply it as useSelector's equality function when a selector creates a flat object, so unchanged field values can prevent a re-render.
useSelector(selector, shallowEqual)| Name | Type | Description |
|---|---|---|
selector | Function | Selector function that derives the value to read from the Redux store. |
equalityFn | Function | React-Redux comparison function used to compare the previous and current selector results. |
A selector result whose equality is determined by shallowEqual; useSelector prevents a re-render when the compared top-level fields are equal.
import { shallowEqual, useSelector } from 'react-redux'
export function TodoSummary() {
const summary = useSelector(
state => ({ count: state.todos.length, firstId: state.todos[0]?.id }),
shallowEqual
)
return <div>{summary.count}</div>
}Pass shallowEqual as useSelector's comparison function when a selector returns a flat object whose fields are primitives or stable references.
A selector returns a newly constructed object containing primitive fields such as count and status.
A selector returns an array whose item references remain unchanged between updates.
A shared hook should consistently use shallow comparison for selected results.
shallowEqual is an equality function that compares the fields of two selector results instead of only comparing their object references. It is useful when a selector returns a newly created flat object whose fields are primitives or stable references.
Follow-up: What happens if a nested object changes internally? shallowEqual only compares the top-level field references, so a nested mutation with the same reference is not detected.
useSelector normally compares the previous and current selector results with strict === reference equality. Passing shallowEqual as the second argument or as equalityFn changes that comparison to field-by-field shallow comparison.
Follow-up: How can the comparison be configured without the positional argument? Put shallowEqual in the options object as the equalityFn property.
A selector that returns a new object normally produces a new reference after each store update, which can trigger a re-render. shallowEqual can avoid that when the returned object's top-level fields remain equal.
Follow-up: What alternative avoids this comparison? Select each needed value separately, or use a memoized selector such as createSelector.
useSelectoruseShallowEqualSelectorcreateSelectorReact-Redux