External state management
A vanilla store feeds non-React code such as an event bridge or service.
Zustand · Const
subscribeWithSelector adds selector-based subscriptions to a Zustand store. It lets subscribers react to selected partial state instead of requiring subscriptions to the entire state.
The selector subscription capability is provided by the subscribeWithSelector middleware. It extends a vanilla store's subscribe method so a listener receives a selected slice instead of every complete-state update; selector and listener arguments can be used to react to targeted changes, with equality support available.
subscribeWithSelector<T>(stateCreatorFn: StateCreator<T, [], []>): StateCreator<T, [['zustand/subscribeWithSelector', never]], []>| Name | Type | Description |
|---|---|---|
stateCreatorFn | StateCreator<T, [], []> | State creator function receiving set, get, and store, normally returning the store state and exposed methods. |
A state creator function typed with the zustand/subscribeWithSelector middleware mutator.
set, get, and store arguments.createStore and applies the middleware around its creator.import { createStore } from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
type PositionStore = {
position: { x: number; y: number }
setPosition: (position: { x: number; y: number }) => void
}
const store = createStore<PositionStore>()(
subscribeWithSelector((set) => ({
position: { x: 0, y: 0 },
setPosition: (position) => set({ position }),
})),
)
const unsubscribe = store.subscribe(
(state) => state.position,
(position) => console.log(position),
)
store.getState().setPosition({ x: 10, y: 20 })
unsubscribe()Creates a vanilla store and listens only when the selected position changes.
A vanilla store feeds non-React code such as an event bridge or service.
A large store contains independent fields and consumers need only one field's changes.
A typed store is built with createStore and should expose selector-aware subscriptions.
The subscribeWithSelector middleware augments a store creator so subscribe can observe a selected part of state. The listener runs when that partial state updates.
Follow-up: How can unnecessary notifications be limited? Use selector-based subscription together with the middleware's equality support.
Wrap the state creator with subscribeWithSelector, then create the store. The resulting store's subscribe method supports subscribing to a selected slice.
Follow-up: What kind of store is shown in the documentation? A vanilla store created with createStore, rather than a React-bound hook.
The middleware accepts a state creator function and returns another state creator function. That returned creator carries the middleware mutator type and can be passed to store creation.
Follow-up: What does the state creator receive? It receives set, get, and store arguments, allowing state and actions to be defined.
createStoresubscribeStateCreatorsetgetstore