Avoid redundant work
Compare flat objects before deciding whether an update is needed.
Zustand · Function
shallow compares two values using top-level equality rules. It is useful for fast checks of simple objects and collections, but it does not recursively compare nested data.
Call shallow with two values to compare them. It checks the values themselves and, for supported collections and objects, compares top-level contents rather than recursively inspecting nested data; it also considers object prototypes.
shallow<T>(a: T, b: T): boolean| Name | Type | Description |
|---|---|---|
a | T | The first value to compare. |
b | T | The second value to compare. |
Returns true when the two inputs are shallowly equal; otherwise returns false.
import { shallow } from 'zustand/vanilla/shallow'
const previous = { count: 1, label: 'ready' }
const next = { count: 1, label: 'ready' }
console.log(shallow(previous, next)) // true
console.log(shallow(previous, { count: 2, label: 'ready' })) // falseCompares two values by their top-level entries.
Compare flat objects before deciding whether an update is needed.
Check whether a selected collection's immediate contents changed.
Compare simple sets without recursively traversing their members.
shallow<T>(a: T, b: T): boolean compares two values and returns a boolean. For objects and collections, it checks top-level values rather than recursively traversing nested structures.
Follow-up: What happens when two objects have different prototypes? They compare unequal because prototype equality is part of the algorithm.
A shallow comparison can treat two separately created flat objects as equal when their top-level properties and values match. It does not inspect nested objects or deeply nested properties.
Follow-up: Why can a nested mutation be missed? If the nested property reference is unchanged, the top-level comparison sees the same reference and does not detect the internal mutation.
For primitive values, shallow agrees with Object.is when the values are the same. For objects, it compares top-level properties and also requires compatible prototypes.
Follow-up: When should a selector use another strategy? Use a different equality approach when correctness depends on changes below the first level.
useShallowcreateWithEqualityFnzustand/vanilla/shallow