Skip to main content

What is a "store" in the context of Zustand?

In the context of Zustand, a store is a centralized state store that contains:

  1. Data (state) - the application's current state;
  2. Actions - functions that change that state;
  3. 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).
  • useCounterStore is 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 elementWhat it is
stateThe current data state
actionsFunctions for changing the state
subscribeThe mechanism for notifying components
getState / setStateImperative access to the state
persist / devtools / middlewareExtensions for extra functionality

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.