What is a "store" in the context of Zustand?
In the context of Zustand, a store is a centralized state store that contains:
- Data (state) - the application's current state;
- Actions - functions that change that state;
- A subscription mechanism - a system that lets React components update automatically when the part of the state they need changes.
A simple definition
A store is an object (or, more precisely, a hook function) that manages state and provides access to it from any part of the application.
Example of a store in Zustand
javascript
import { create } from 'zustand'
interface CounterState {
count: number
increase: () => void
decrease: () => void
}
// Create the store
export const useCounterStore = create<CounterState>((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}))What happens here:
create()creates the store.- Inside it, a function is passed that receives
set- a way to update the state. - We return an object that has fields (state) and functions (actions).
useCounterStoreis a React hook that can be called in any component to get access to the state.
How a store works "under the hood"
Zustand creates a single global store (independent of React), and the useStore() hook simply:
- subscribes the component to the data it needs;
- triggers a re-render only for that component when it changes.
This makes Zustand:
- very fast (no Context API);
- simple to use outside React (in plain JS);
- convenient for SSR and unit tests.
Accessing the store outside React
A Zustand store is not just a React hook.
It also has .getState() and .setState() methods for direct access:
javascript
import { useCounterStore } from './store'
// Get the state outside React
console.log(useCounterStore.getState().count)
// Change the state outside React
useCounterStore.setState({ count: 10 })This is useful, for example, in:
- API handlers;
- services that do not depend on React;
- tests and middleware.
Summary
| Store element | What it is |
|---|---|
| state | The current data state |
| actions | Functions for changing the state |
| subscribe | The mechanism for notifying components |
| getState / setState | Imperative access to the state |
| persist / devtools / middleware | Extensions for extra functionality |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.