Sub topic 9
Reading and updating state outside React
This chapter assumes you can build a store with create, read it with selectors, and write actions with set. It also assumes you know what a module-level singleton is in JavaScript. A store from create is not locked inside React, and this chapter shows how to use that.
The hook is also a store object
The value returned by create is a function you call as a hook inside components. It also carries three methods, so the same object works in plain TypeScript modules, event listeners, timers, and tests.
| Method | What it does |
|---|---|
| `getState()` | Returns the current state object, including actions. |
| `setState(partial, replace?)` | Updates state the same way `set` does inside the store. |
| `subscribe(listener)` | Calls `listener(state, prevState)` after every change and returns an unsubscribe function. |
The following example uses the counter store from earlier in this tutorial.
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 a snapshot. The value in current is a plain number and will not update when the store changes. Call getState() again whenever you need a fresh value.
setState merges the partial object into the existing state, exactly like set. It also accepts a function, setState((state) => ({ count: state.count + 1 })), when the new value depends on the old one.
Where this is useful
Code outside React often needs the store, because React is not the only thing that runs in an application. Common cases:
- An HTTP client that attaches an auth token to every request.
- A WebSocket or server-sent-events handler that pushes incoming messages into state.
- A router guard or a global error handler that must read or clear user state.
- A timer,
storageevent listener, ormatchMedialistener that writes into state. - Tests that set up state directly (covered in a later chapter).
Here is an API helper that reads a token and logs the user out on a 401 response. It does not use React at all.
import { create } from 'zustand'
interface AuthState {
token: string | null
setToken: (token: string | null) => void
logout: () => void
}
export const useAuthStore = create<AuthState>()((set) => ({
token: null,
setToken: (token) => set({ token }),
logout: () => set({ token: null }),
}))
export async function apiFetch(input: string, init: RequestInit = {}) {
const token = useAuthStore.getState().token
const headers = new Headers(init.headers)
if (token) headers.set('Authorization', `Bearer ${token}`)
const response = await fetch(input, { ...init, headers })
if (response.status === 401) {
useAuthStore.getState().logout()
}
return response
}A component showing a "Log in" button reads the same state with useAuthStore((s) => s.token). When apiFetch calls logout(), that component re-renders. One store serves both sides.
getState in render versus a selector
Calling useCounterStore.getState().count inside a component body works, but it does not subscribe the component. The component will not re-render when count changes. This is a common mistake. A stale screen with no error is the usual symptom.
Use the following rule:
- If the value affects what is rendered, use the hook with a selector.
- If you need the value at a moment in time, such as inside an event handler, use
getState().
Reading in an event handler is often better than selecting. Suppose a "Save" button needs the draft text only when clicked:
import { useDraftStore } from './draftStore'
function SaveButton() {
const handleClick = () => {
const { text } = useDraftStore.getState()
void fetch('/api/save', { method: 'POST', body: text })
}
return <button onClick={handleClick}>Save</button>
}SaveButton does not re-render when the draft changes, because it never subscribed. It also cannot send a stale value, because it reads the state at click time.
Subscribing to changes
subscribe calls your listener after every state change, whichever field changed. The listener receives the new state and the previous state. It returns a function. Call that function to stop listening.
Two rules keep subscriptions safe:
- Always keep the returned unsubscribe function and call it when the owner goes away. In a React effect, return it from the effect.
- Do not call
setStateunconditionally inside a listener for the same store. That triggers the listener again and loops forever. ComparestateandprevStatefirst.
A subscription inside a component belongs in useEffect:
import { useEffect } from 'react'
import { useCounterStore } from './counterStore'
function TitleSync() {
useEffect(() => {
return useCounterStore.subscribe((state) => {
document.title = `Count: ${state.count}`
})
}, [])
return null
}The effect returns the unsubscribe function, so React cleans up when the component unmounts.
Subscribing to one field
Plain subscribe takes only a listener, so you must compare old and new values yourself. The subscribeWithSelector middleware adds an overload that takes a selector and fires only when the selected value changes.
import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
interface ThemeState {
theme: 'light' | 'dark'
fontSize: number
toggleTheme: () => void
setFontSize: (size: number) => void
}
export const useThemeStore = create<ThemeState>()(
subscribeWithSelector((set) => ({
theme: 'light',
fontSize: 16,
toggleTheme: () =>
set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
setFontSize: (fontSize) => set({ fontSize }),
})),
)
const unsubscribe = useThemeStore.subscribe(
(state) => state.theme,
(theme, prevTheme) => {
console.log(`theme ${prevTheme} -> ${theme}`)
document.documentElement.dataset.theme = theme
},
)
useThemeStore.getState().setFontSize(18)
useThemeStore.getState().toggleTheme()
unsubscribe()The setFontSize call does not run the listener. The toggleTheme call does. Selector subscriptions compare with Object.is by default. An optional third argument can supply equalityFn when the selector returns an object.
Replacing state instead of merging
setState takes a second argument, replace. With true, the given object replaces the whole state instead of merging into it.
import { useCounterStore } from './counterStore'
const initial = useCounterStore.getState()
useCounterStore.setState({ count: 5 })
useCounterStore.setState(initial, true)Use this to reset a store. In TypeScript, a replacement must contain the full state shape, including actions. Passing a partial object with true would drop the actions, which is why the types complain. Saving getState() once at module load, as above, gives a complete snapshot to restore.
Edge cases and gotchas
- Module-level state is shared. The store is created once when its module is first imported. All code in the same JavaScript runtime sees the same data. On a server that renders for many users, this means one user's state can leak into another's request. Per-request stores are covered in the chapter on vanilla and context stores.
- Listeners run synchronously.
setStatefinishes by calling every listener before it returns. A slow listener slows down the update. - Snapshots go stale. Do not store the result of
getState()in a long-lived variable and expect it to track changes. Store the hook and callgetState()when needed. - Mutations bypass notification. Writing
useCounterStore.getState().count = 5changes the object but notifies no one. Always go throughsetStateor an action. - Actions are stable. Actions read from
getState()do not change between renders, so callinguseStore.getState().increment()is safe anywhere.
Summary of when to use each tool
| Situation | Use |
|---|---|
| Value is shown in JSX | Hook with a selector |
| Value is needed once inside an event handler or async function | `getState()` |
| React to changes from non-React code | `subscribe` |
| React to one field only | `subscribe` with `subscribeWithSelector` |
| Reset a store | `setState(initialState, true)` |
Exercise
A module-level function logCount() runs every second from setInterval and must print the latest count from useCounterStore. A teammate wrote const { count } = useCounterStore.getState() once at the top of the module and prints count inside the interval. Why does it always print the same number, and how do you fix it?
Show answer
Destructuring copies the value from a snapshot taken once at load time. The number never updates because it is a plain variable, not a live reference. Move the getState() call inside the interval callback, as in setInterval(() => console.log(useCounterStore.getState().count), 1000), so each tick reads the current state.
Exercise
You want to update document.title whenever theme changes in useThemeStore, but not when fontSize changes. Which API do you use, and what must you do when the owning component unmounts?
Show answer
Use subscribe with a selector ((state) => state.theme) and a listener, which needs the subscribeWithSelector middleware on the store. Subscribe inside useEffect and return the unsubscribe function from the effect, so the listener is removed when the component unmounts.