External side effects
Run logging, analytics, or synchronization code when state changes outside React rendering.
Zustand · Module
useStore.subscribe registers a callback that runs when the Zustand store updates. It returns an unsubscribe function for removing the listener.
useStore.subscribe is the subscription utility attached to a Zustand store hook. It registers a callback that runs when the store state updates and returns a cleanup function, making it suitable for external effects that should be explicitly unsubscribed.
useStore.subscribe(listener)| Name | Type | Description |
|---|---|---|
listener | (state) => void | Callback invoked when the store's state updates; it receives the updated state. |
An unsubscribe function that removes the registered listener.
subscribe registers a callback for store-state updates.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()Registers an external listener for store updates, then removes it by calling the returned unsubscribe function.
Run logging, analytics, or synchronization code when state changes outside React rendering.
Attach a listener for the lifetime of a component and remove it during effect cleanup.
Observe a selected state slice with selector and equality behavior.
subscribe utility do?subscribe registers a callback that runs whenever the store's state updates. It returns an unsubscribe function, which should be called when the listener is no longer needed.
Follow-up: How would you avoid leaving a listener active in a component? Register it inside an effect and return the unsubscribe function from that effect's cleanup.
The callback can receive the updated state, allowing external code to react without rendering a component. The documentation demonstrates destructuring a state property inside the callback.
Follow-up: When would you prefer a selector-based subscription? Use subscribeWithSelector when you need to observe only a selected slice with equality support.
subscribe be used outside React rendering?A store hook created with create exposes API utilities including setState, getState, getInitialState, and subscribe. This lets code outside React coordinate with the store.
Follow-up: How can a vanilla store be consumed in React? Pass the vanilla store to useStore, optionally with a selector.
createuseStoresubscribeWithSelectorgetStatesetState