Reduce unnecessary component updates
A store frequently selects derived objects or collections and needs a comparator tailored to value equality.
Zustand · Function
createWithEqualityFn creates a React hook store like create, while allowing a default equality function. Equality checks give finer control over selector-driven re-renders.
Call createWithEqualityFn with a state creator and optionally a default comparator. The returned hook exposes store APIs, accepts a selector plus an equality function, and can avoid re-renders when selected values compare equal.
createWithEqualityFn<T>()(stateCreatorFn: StateCreator<T, [], []>, defaultEqualityFn?: <U>(a: U, b: U) => boolean)| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | Function receiving set, get, and store; normally returns the state and exposed methods. |
defaultEqualityFn | <U>(a: U, b: U) => boolean | Optional comparator used to skip re-renders; defaults to Object.is. |
A React hook with API utilities attached; it supports selector-based reads and equality-based render skipping.
import { createWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/shallow'
type BearState = { bears: number; increase: () => void }
const useBearStore = createWithEqualityFn<BearState>((set) => ({
bears: 0,
increase: () => set((state) => ({ bears: state.bears + 1 })),
}), shallow)
export function BearCount() {
const bears = useBearStore((state) => state.bears)
return <button onClick={useBearStore.getState().increase}>{bears}</button>
}Creates a React store whose default selector comparison uses shallow equality.
A store frequently selects derived objects or collections and needs a comparator tailored to value equality.
An application consistently uses one comparison policy across selectors in a store.
A v5 application needs custom equality behavior that create no longer provides.
It is a React store factory similar to create, but it lets you provide a default equality function. The resulting hook also has the store API utilities attached.
Follow-up: How can a component override the default comparison? Pass a selector and an equality function when calling the returned hook.
The state creator receives set, get, and store, and normally returns the state and actions to expose. The optional defaultEqualityFn defaults to Object.is.
Follow-up: Why might a custom comparator help? It can prevent re-renders when the selected result is considered equal by that comparator.
Importing it from zustand/traditional requires use-sync-external-store because that entry point relies on useSyncExternalStoreWithSelector. This dependency is not optional for that usage.
Follow-up: What is the v5 alternative when custom equality is needed? Use createWithEqualityFn rather than create, because v5 create does not support customizing equality.
createuseStoreWithEqualityFnshallowuseSyncExternalStoreWithSelector