Sub topic 9
Reading and updating state outside React
This chapter assumes you can write a Zustand store with create, read it with selectors, and update it with set. It also assumes you know basic TypeScript modules. Here you will use a store from code that is not a React component.
Why the hook is also a store object
The function returned by create is a React hook. It also carries three methods: getState, setState and subscribe. These work anywhere, including in plain modules, event handlers set up at startup, and timers. They do not need a component or a provider.
import { useCounterStore } from './counterStore'
const current = useCounterStore.getState().count
useCounterStore.setState({ count: 10 })
const unsubscribe = useCounterStore.subscribe((state, prevState) => {
console.log('count changed from', prevState.count, 'to', state.count)
})
unsubscribe()getState()returns the current state object, including your actions.setState(partial)behaves likesetinside the store. It merges the partial object into the existing state.subscribe(listener)calls the listener after every change. It receives the new state and the previous state. It returns a function that removes the listener.
How the pieces fit together
Common uses
A typical case is a network layer that needs a value from the store. An API client can read a token at request time:
import { useAuthStore } from './authStore'
export async function apiFetch(path: string) {
const token = useAuthStore.getState().token
return fetch(path, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
})
}Calling an action works the same way: useAuthStore.getState().logout(). Use this when a 401 response handler needs to sign the user out.
Gotchas
getState()is a snapshot. If you store the result in a variable, that variable will not update. CallgetState()again when you need a fresh value.- Reading with
getState()inside a component does not subscribe the component. The component will not re-render when the value changes. Inside components, use the hook with a selector. subscribelisteners keep running until you call the returned function. In a component, register the listener inuseEffectand return the unsubscribe function as cleanup.setState(newState, true)replaces the whole state instead of merging. This removes any key you leave out, including actions, so use it only with a complete state object. Tests use it to reset a store.
Subscribing from a component
import { useEffect } from 'react'
import { useCounterStore } from './counterStore'
function CountLogger() {
useEffect(() => {
const unsubscribe = useCounterStore.subscribe((state) => {
document.title = `Count: ${state.count}`
})
return unsubscribe
}, [])
return null
}This updates the document title on every change without re-rendering CountLogger. Side effects that do not change the UI are a good fit for subscribe.
Exercise
A component reads const count = useCounterStore.getState().count in its body and shows it. A button elsewhere calls increment. Why does the displayed number not change, and what is the fix?
Show answer
getState() returns a one-time snapshot and does not subscribe the component, so React never re-renders it when the store changes. Replace the line with const count = useCounterStore((state) => state.count), which subscribes the component through a selector.