External monitoring
Log or inspect state changes without causing a React component subscription.
Zustand · Type Alias
StoreApi.subscribe registers a callback that runs when the Zustand store updates. It is useful for external state management and returns an unsubscribe function for cleanup.
StoreApi.subscribe registers a callback that runs when the store state updates. It returns an unsubscribe function, allowing external code to observe a store without using a React component subscription.
store.subscribe(listener): () => void| Name | Type | Description |
|---|---|---|
listener | (state: T) => void | A listener callback invoked when the store state updates; the callback receives the current state. |
An unsubscribe function that removes the registered listener.
import { create } from 'zustand'
type PositionState = {
position: { x: number; y: number }
setPosition: (position: { x: number; y: number }) => void
}
const usePositionStore = create<PositionState>((set) => ({
position: { x: 0, y: 0 },
setPosition: (position) => set({ position }),
}))
const unsubscribe = usePositionStore.subscribe(({ position }) => {
console.log('new position', position)
})
usePositionStore.getState().setPosition({ x: 10, y: 20 })
unsubscribe()Creates a store, registers an external listener with subscribe, updates state, and removes the listener.
Log or inspect state changes without causing a React component subscription.
Synchronize store changes with an imperative API or another state system.
It is the store API method for observing state changes outside the component-rendering path. Calling it registers a callback that fires whenever the store updates and returns a function for removing that subscription.
Follow-up: How can a component clean up a subscription? Store the returned function and invoke it during the effect cleanup phase.
The callback receives the current store state, so external code can react to updates such as logging, synchronization, or imperative rendering. The API is attached to stores created with create.
Follow-up: Why might external code prefer this API? It can observe updates without making the observation itself a React render subscription.
The method returns an unsubscribe function. Calling that function removes the listener and prevents later updates from invoking it.
Follow-up: What lifecycle rule follows from this? Every long-lived subscription should have a matching unsubscribe call to avoid stale listeners.
creategetStatesetStategetInitialStatesubscribeWithSelector