पाठ 20 / 25
Stores Outside React and with TypeScript
getState, setState, subscribe and vanilla stores.
The hook is also a store
The hook returned by create carries the store API: useStore.getState(), useStore.setState(partial) and useStore.subscribe(listener) work in plain modules such as API clients, WebSocket handlers or router guards. createStore from zustand/vanilla builds a store with no React at all; components read it with useStore(store, selector) from zustand. For server-side rendering or per-test isolation, create the vanilla store inside a component and share it through React Context instead of a module-level singleton, so requests do not share state.
Auth token outside components
A vanilla store, a fetch wrapper and a hook.
import { createStore } from 'zustand/vanilla';
import { useStore } from 'zustand';
type AuthState = { token: string | null; setToken: (t: string | null) => void };
export const authStore = createStore<AuthState>()((set) => ({
token: null,
setToken: (token) => set({ token }),
}));
// plain module: no React involved
export async function apiFetch(path: string) {
const { token } = authStore.getState();
return fetch(path, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
}
// react to changes anywhere
const unsubscribe = authStore.subscribe((state, prev) => {
if (prev.token && !state.token) console.info('signed out');
});
// inside components
export const useAuth = <T,>(selector: (s: AuthState) => T) => useStore(authStore, selector);Beware module singletons on the server
In frameworks that render on the server, a module-level store is shared by every request. Create a store per request and provide it via Context; check your framework and Zustand docs for the recommended setup.
त्वरित जाँच: How can a non-React module read a Zustand store created with create?
- It cannot; Zustand only works in components
- Call useStore.getState()
- Import the Provider
- Dispatch a getState action
Answer
Call useStore.getState() — The hook exposes the vanilla store API.