External state synchronization
Run side effects or synchronize external systems when store state changes.
Zustand · Module
subscribe registers a listener for updates to a Zustand vanilla store. It is useful for reacting to state changes in external, non-React code.
A store created with createStore exposes subscribe, which registers a callback that runs whenever the store state updates. The returned cleanup function removes that listener, making the API suitable for reacting to changes outside React components.
store.subscribe(listener)| Name | Type | Description |
|---|---|---|
listener | (state: T) => void | Callback invoked when the store state updates; it receives the current state. |
An unsubscribe function that removes the registered listener.
subscribe as one of its public API utilities.subscribe registers a callback that reacts to store state updates.subscribe method.import { createStore } from 'zustand/vanilla'
type State = { count: number }
const store = createStore<State>(() => ({ count: 0 }))
const unsubscribe = store.subscribe((state) => {
console.log(state.count)
})
store.setState({ count: 1 })
unsubscribe()
Creates a vanilla store, registers a listener for state updates, changes the state, and then removes the listener.
Run side effects or synchronize external systems when store state changes.
Observe a vanilla store from services, event handlers, or other non-React code.
Trigger rendering or other updates when a store changes outside a component.
subscribe API do?subscribe registers a callback for store updates and returns an unsubscribe function. The callback receives the updated state, so it can be used for external state management without a React component.
Follow-up: How would you stop listening? Call the function returned by subscribe; this removes that subscription.
subscribe available on a Zustand vanilla store?A vanilla store returned by createStore exposes subscribe alongside state access and mutation utilities. This lets non-React code observe state changes directly.
Follow-up: Why use a vanilla store here? It provides the store API without requiring a React hook or component lifecycle.
The basic subscription callback receives the store state after updates. For more granular subscriptions, Zustand documents the subscribeWithSelector middleware, which supports subscribing to partial state updates.
Follow-up: When would granular subscriptions help? They let external code react to a selected slice instead of every full-store update.
createStoresetStategetStategetInitialStatesubscribeWithSelector