Skip to content
D
Documentation

Customize equality checks

how-to
4 min readUpdated

Use custom equality when a selector's output needs a comparison other than Object.is, or when an imperative listener needs only part of the state. Equality determines whether a selected value counts as changed; it does not prevent the store from updating.

This page starts from the project in the React quick start. You add two position stores: one bound to React, and one vanilla store shared by a React view and an imperative dot renderer.

create in Zustand v5 does not accept a custom equality function. Use createWithEqualityFn for a bound hook, or useStoreWithEqualityFn to consume a vanilla store. Both come from zustand/traditional and require use-sync-external-store.

Install the dependencies used below. The quick start already supplies React and Zustand; this command also adds the binding's peer dependency:

bash
npm install zustand react use-sync-external-store

For shallow comparison alone, you can keep create and wrap a selector with useShallow. See Select computed state for that approach.

2. Create bound and vanilla stores

Add src/position-stores.ts. shallow from zustand/vanilla/shallow supplies the bound hook's default equality. createStore creates the independent vanilla store. Wrap its initializer with subscribeWithSelector to give imperative subscribers a selector, a comparison function, and an immediate-notification option.

ts
import { createStore } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import { createWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/vanilla/shallow'

type PositionState = {
  position: { x: number; y: number }
  setPosition: (position: PositionState['position']) => void
}

export const useBoundPosition = createWithEqualityFn<PositionState>()(
  (set) => ({
    position: { x: 20, y: 20 },
    setPosition: (position) => set({ position }),
  }),
  shallow,
)

export const positionStore = createStore<PositionState>()(
  subscribeWithSelector((set) => ({
    position: { x: 20, y: 20 },
    setPosition: (position) => set({ position }),
  })),
)

The bound store's default equality applies to hook calls, not to imperative subscriptions; see How Zustand works for the shared store methods and the hook-versus-vanilla distinction.

3. Customize bound and vanilla React selections

Add src/EqualityExample.tsx. The bound view uses the default shallow comparison for its coordinates. Its separate X-only view passes a custom equality function as the hook's second argument, overriding that default for this selection.

The vanilla view passes its store, selector, and shallow from zustand/shallow to useStoreWithEqualityFn. This export is the same comparison function as the vanilla entry point's export.

tsx
import { useEffect, useRef } from 'react'
import { useStoreWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/shallow'
import { positionStore, useBoundPosition } from './position-stores'

function BoundX() {
  const selected = useBoundPosition(
    (state) => ({ x: state.position.x }),
    (previous, next) => previous.x === next.x,
  )
  return <p>Custom equality selection — X: {selected.x}</p>
}

function BoundPosition() {
  const position = useBoundPosition((state) => state.position)
  const setPosition = useBoundPosition((state) => state.setPosition)

  useEffect(() => {
    const unsubscribe = useBoundPosition.subscribe((state, previous) => {
      console.log('Bound position update', previous.position, state.position)
    })
    return unsubscribe
  }, [])

  return (
    <section>
      <h2>Bound store</h2>
      <p>X: {position.x}, Y: {position.y}</p>
      <BoundX />
      <button type="button" onClick={() => {
        setPosition({ ...position, x: position.x + 10 })
      }}>Move right</button>
      <button type="button" onClick={() => {
        setPosition({ ...position, y: position.y + 10 })
      }}>Move down</button>
      <button type="button" onClick={() => {
        setPosition({ ...position })
      }}>Copy coordinates</button>
    </section>
  )
}

function VanillaPosition() {
  const position = useStoreWithEqualityFn(
    positionStore,
    (state) => state.position,
    shallow,
  )
  const setPosition = useStoreWithEqualityFn(
    positionStore,
    (state) => state.setPosition,
    shallow,
  )

  return (
    <section>
      <h2>Vanilla store</h2>
      <p>X: {position.x}, Y: {position.y}</p>
      <button type="button" onClick={() => {
        setPosition({ ...position, x: position.x + 10 })
      }}>Move right</button>
      <button type="button" onClick={() => {
        setPosition({ ...position, y: position.y + 10 })
      }}>Move down</button>
      <button type="button" onClick={() => {
        setPosition({ ...position })
      }}>Copy coordinates</button>
    </section>
  )
}

function SubscribedDot() {
  const dotRef = useRef<HTMLDivElement>(null)
  const reportRef = useRef<HTMLOutputElement>(null)

  useEffect(() => {
    const dot = dotRef.current
    const report = reportRef.current
    if (!dot || !report) return

    const unsubscribe = positionStore.subscribe(
      (state) => state.position,
      (position, previous) => {
        dot.style.transform = `translate(${position.x}px, ${position.y}px)`
        report.textContent =
          `Previous: ${previous.x}, ${previous.y}; current: ${position.x}, ${position.y}`
      },
      { equalityFn: shallow, fireImmediately: true },
    )
    return unsubscribe
  }, [])

  return (
    <section>
      <h2>Selected-state subscription</h2>
      <output ref={reportRef} aria-live="polite" />
      <div
        onPointerMove={(event) => {
          const bounds = event.currentTarget.getBoundingClientRect()
          positionStore.getState().setPosition({
            x: event.clientX - bounds.left,
            y: event.clientY - bounds.top,
          })
        }}
        style={{ position: 'relative', height: 200, width: 320,
          background: '#eee', marginTop: 16 }}
      >
        <div ref={dotRef} style={{ position: 'absolute', left: -5, top: -5,
          width: 10, height: 10, borderRadius: '50%', background: 'red',
          pointerEvents: 'none' }} />
      </div>
    </section>
  )
}

export default function EqualityExample() {
  return (
    <main style={{ minHeight: 400, display: 'grid', gap: 24 }}>
      <h1>Position equality</h1>
      <BoundPosition />
      <VanillaPosition />
      <SubscribedDot />
    </main>
  )
}

In the quick start's entry file, replace the counter import with EqualityExample from ./EqualityExample.tsx and render <EqualityExample /> instead, leaving the rest of the mounting setup unchanged.

bash
npm run build
npm run dev

Open Vite's local URL. Both coordinate views start at 20, 20; a red dot appears in the gray area. Move right changes X, and Move down changes Y for the corresponding store. The stores are independent.

Copy coordinates writes a new object with the same top-level values. The shallow-equal React selections do not trigger a store-driven re-render. In the bound store, the full-state subscription still logs the update. The custom X selection considers two outputs equal whenever their X values match; it does not subscribe to Y. Equality does not block renders caused by a parent or local React state.

Subscribing to state updates

Use an imperative subscription to drive a DOM element or another system without making it a React state consumer. The SubscribedDot component above follows these steps:

  1. Subscribe after the DOM elements mount, inside useEffect.
  2. Select state.position. The listener receives the next selected position and the previous selected position, not the full store.
  3. Pass fireImmediately: true to draw the current position as soon as you subscribe. That first callback receives the current selection as both arguments.
  4. Return the unsubscribe function from the effect to remove the listener on unmount.

Move the pointer inside the gray area: the red dot follows it, the vanilla React coordinates update, and the output reports the previous and current coordinates. The vanilla store's buttons update the same dot through the same subscription. Copy coordinates leaves the output unchanged because equalityFn: shallow filters that notification.

The bound store's one-argument subscribe(listener) illustrates a full-state subscription with cleanup. Adding subscribeWithSelector enables the additional subscribe(selector, listener, options) form; it does not remove the full-state form. Notifications run synchronously when the store updates.

Compare values shallowly

shallow<T>(a, b) returns a boolean. It compares top-level values, not nested contents. You can also call it outside a selector. Run this complete example in a browser module or your TypeScript project:

ts
import { shallow } from 'zustand/shallow'

const first = { x: 20, y: 20 }
const second = { x: 20, y: 20 }

console.log('Same reference:', Object.is(first, second)) // false
console.log('Same coordinates:', shallow(first, second)) // true
console.log('Same primitive:', shallow(20, 20)) // true
console.log('Same array values:', shallow([20, 20], [20, 20])) // true
console.log('Same set values:', shallow(new Set([1, 2]), new Set([2, 1]))) // true
console.log('Same map entries:', shallow(
  new Map([['x', 20]]), new Map([['x', 20]]),
)) // true
console.log('Separate nested objects:', shallow(
  { position: first }, { position: second },
)) // false

For ordinary objects, matching top-level keys must have Object.is-equal values. Arrays compare values at their indices; Maps compare key/value entries, and Sets compare membership without depending on insertion order. Objects with different prototypes compare unequal. Nested objects need the same reference to compare equal at that level.

Equality and subscription options

In the table, U is the selector's output type.

Option or argumentTypeDefaultWhat it does
createWithEqualityFn's defaultEqualityFn<U>(a: U, b: U) => booleanObject.isSets the default comparison for bound-hook selections. It must work for every selected output type.
Bound hook's second argument(a: U, b: U) => booleanStore's default equalityOverrides equality for that hook call.
useStoreWithEqualityFn's third argument(a: U, b: U) => booleanObject.is comparison when omittedCompares that vanilla-store consumer's selected output.
Selected subscription's equalityFn(a: U, b: U) => booleanObject.isSuppresses the listener when the comparison returns true.
Selected subscription's fireImmediatelybooleanNo immediate callbacktrue calls the listener during subscription setup; false waits for a selected-state change.

Keep a custom comparator aligned with what the component reads: returning true tells the binding to retain the previous selection. Use immutable updates when changing objects, and see Select computed state for stable computed outputs.

Explore the live Zustand demo for the store-and-selector interaction. For the equality-enabled API, compare these samples with the bound-hook example and vanilla-hook example.

Was this page helpful?

Customize equality checks — zustand · GPT-6.1 Sol