Selector equality
Compare selector results containing several top-level fields without recursively checking nested data.
Zustand · Const
shallow compares two values using top-level equality rules. It is useful for fast checks of simple structures, but it does not recursively compare nested data.
The shallow utility compares two values without recursively inspecting nested data. It checks top-level properties, supports simple structures such as objects and sets, and can be used as an equality function when selector results should be compared by their contents rather than wrapper identity.
shallow<T>(a: T, b: T): boolean| Name | Type | Description |
|---|---|---|
a | T | First value to compare. |
b | T | Second value to compare. |
A boolean: true when the two inputs are shallowly equal, otherwise false.
import { shallow } from 'zustand/shallow'
const previous = { count: 1, label: 'one' }
const next = { count: 1, label: 'one' }
console.log(shallow(previous, next)) // true
console.log(shallow(previous, { count: 2, label: 'one' })) // falseCompares two objects by their top-level properties and values.
Compare selector results containing several top-level fields without recursively checking nested data.
Check whether simple object values changed while avoiding a deep comparison.
Compare sets when their entries are the relevant data.
shallow utility do?shallow returns a boolean indicating whether two values are equal according to a shallow comparison. For objects, it compares top-level properties and their values rather than recursively traversing nested data.
Follow-up: What happens when nested values differ? The comparison can still return true if the top-level property references themselves are unchanged, because nested contents are not inspected.
shallow compare primitive values?For primitive values such as strings, numbers, booleans, and BigInts, shallow agrees with Object.is when the values are the same. For structured values, it performs a top-level comparison.
Follow-up: Why can two separately created objects compare unequal? Their top-level property values may differ by reference, even if nested contents look equivalent.
The utility is useful when comparing simple data structures whose relevant changes occur at the top level. It can also compare sets using their entries, while retaining shallow-comparison limitations.
Follow-up: When should a deeper comparison be used? Use a separate deep-comparison strategy when nested content changes must be detected rather than only top-level changes.
useShallowcreateWithEqualityFnuseStoreWithEqualityFn