State & Data: Zustand (Client Store Architecture)
Zustand (Client Store): Implement a minimalist, hook-based client-side store without excessive boilerplate.
Managing global client state in React historically meant choosing between two extremes:
- **The Context API dilemma:** React’s built-in createContext propagates changes down the component tree. Whenever any piece of a context value updates, every consuming component re-renders by default. Preventing cascading renders requires splitting contexts across multiple providers, leading to deeply nested "provider pyramids."
- **The Redux boilerplate burden:** Traditional state containers introduced heavy ceremony—action creators, dispatchers, reducer switch statements, and middleware pipelines—just to flip a boolean or store a modal state.
Zustand solves this by implementing an unopinionated, hook-based external store pattern. It keeps state outside the React component tree entirely, providing reactive, fine-grained subscriptions via selector functions.
## 1. Core Architectural Pillars
### 1.1 State Outside the React Tree
A Zustand store is a standalone JavaScript closure holding state and actions in heap memory. It operates without an enclosing <Provider> at the root of your application.
```text
[ Standalone Store (Heap Memory) ]
├── State: { count, theme, user }
└── Actions: { increment, toggleTheme }
│
│ Reactive Subscriptions via Selectors
│ (Referential equality via Object.is)
▼
┌───────────────────────┼───────────────────────┐
│ │ │
▼ ▼ ▼
Component A Component B Component C
Reads: state.count Reads: state.theme Reads actions ONLY
(Re-renders on count) (Re-renders on theme) (Zero re-renders)
```
### 1.2 Fine-Grained Subscriptions with useSyncExternalStore
Under the hood, Zustand binds to React using useSyncExternalStore. When a component queries a slice of state:
```ts
const count = useStore((state) => state.count);
```
The component subscribes specifically to changes in state.count. If an unrelated property like state.theme updates elsewhere in the app, this component skips reconciliation completely.
## 2. Store Implementation: Colocating State and Actions
In Zustand, actions live directly inside the store object alongside the values they mutate. There are no separate dispatch functions or reducer files.
```ts
// src/stores/useCounterStore.ts
import { create } from 'zustand';
interface CounterState {
count: number;
increment: () => void;
decrement: () => void;
setByAmount: (amount: number) => void;
reset: () => void;
}
export const useCounterStore = create((set) => ({
count: 0,
// 1. Functional updater: safely derives next state from previous state
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
// 2. Direct partial update: merges shallowly into root state
setByAmount: (amount) => set({ count: amount }),
reset: () => set({ count: 0 }),
}));
```
### Component Consumption
```ts
// Component 1: Subscribes to count; re-renders when count changes
export function CounterDisplay() {
const count = useCounterStore((state) => state.count);
return
);
}
```
## 3. Selector Performance & Equality Checks
A frequent performance regression happens when extracting multiple properties into a newly allocated object literal:
```ts
// ❌ ANTI-PATTERN: Returns a new object reference on every evaluation
const { name, email } = useUserStore((state) => ({
name: state.name,
email: state.email,
}));
// Because { ... } !== { ... }, this component re-renders on ANY store update!
```
### Solution A: Atomic Selectors (Recommended)
Extract each primitive individually so React checks standard reference equality:
```ts
// ✅ BEST PRACTICE: Subscribes to stable scalar primitives
const name = useUserStore((state) => state.name);
const email = useUserStore((state) => state.email);
```
### Solution B: Using useShallow
When grouping properties into an object or array is necessary, use useShallow from zustand/react/shallow. It runs a shallow comparison (=== across top-level keys) instead of checking object reference identity:
```ts
// ✅ CORRECT: Only triggers a re-render if name or email values actually change
import { useShallow } from 'zustand/react/shallow';
const { name, email } = useUserStore(
useShallow((state) => ({
name: state.name,
email: state.email,
}))
);
```
## 4. Scalable Architecture: The Slice Pattern
As an application scales, keeping everything in one store file becomes unwieldy. The Slice Pattern organizes state by business domain while compiling everything into a unified hook.
```text
src/stores/
├── slices/
│ ├── authSlice.ts # Authentication, user session, tokens
│ ├── cartSlice.ts # Cart items, calculated totals
│ └── uiSlice.ts # Modals, sidebars, active drawer states
└── useAppStore.ts # Unified root store hook
```
### 4.1 Defining Individual Slices
```ts
// src/stores/slices/authSlice.ts
import { StateCreator } from 'zustand';
import { RootStore } from '../useAppStore';
export interface AuthSlice {
user: { id: string; name: string } | null;
isAuthenticated: boolean;
login: (userData: { id: string; name: string }) => void;
logout: () => void;
}
export const createAuthSlice: StateCreator<
RootStore,
[],
[],
AuthSlice
> = (set) => ({
user: null,
isAuthenticated: false,
login: (user) => set({ user, isAuthenticated: true }),
logout: () => set({ user: null, isAuthenticated: false }),
});
```
```ts
// src/stores/slices/cartSlice.ts
import { StateCreator } from 'zustand';
import { RootStore } from '../useAppStore';
export interface CartItem {
id: string;
price: number;
qty: number;
}
export interface CartSlice {
items: CartItem[];
addItem: (item: CartItem) => void;
clearCart: () => void;
}
export const createCartSlice: StateCreator<
RootStore,
[],
[],
CartSlice
> = (set) => ({
items: [],
addItem: (newItem) =>
set((state) => {
const existing = state.items.find((i) => i.id === newItem.id);
if (existing) {
return {
items: state.items.map((i) =>
i.id === newItem.id ? { ...i, qty: i.qty + newItem.qty } : i
),
};
}
return { items: [...state.items, newItem] };
}),
clearCart: () => set({ items: [] }),
});
```
### 4.2 Merging into the Unified Root Store
```ts
// src/stores/useAppStore.ts
import { create } from 'zustand';
import { AuthSlice, createAuthSlice } from './slices/authSlice';
import { CartSlice, createCartSlice } from './slices/cartSlice';
// Compose slice interfaces into a single type contract
export type RootStore = AuthSlice & CartSlice;
export const useAppStore = create()((...a) => ({
...createAuthSlice(...a),
...createCartSlice(...a),
}));
```
### Consuming the Root Store
```ts
export function CheckoutButton() {
const isAuthenticated = useAppStore((state) => state.isAuthenticated);
const items = useAppStore((state) => state.items);
const clearCart = useAppStore((state) => state.clearCart);
const handleCheckout = () => {
if (!isAuthenticated) return alert('Please sign in first');
clearCart();
};
return ;
}
```
## 5. Production Middleware: Persist, DevTools & Immer
Zustand supports functional middleware composition to handle persistence, debugging, and nested mutations without extra boilerplate:
```ts
// src/stores/useSettingsStore.ts
import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
interface SettingsState {
theme: 'light' | 'dark' | 'system';
notifications: {
email: boolean;
push: boolean;
};
setTheme: (theme: 'light' | 'dark' | 'system') => void;
toggleEmailNotifications: () => void;
}
export const useSettingsStore = create()(
// 1. DevTools: connects mutations to Redux DevTools extension
devtools(
// 2. Persist: serializes selected state slices to storage
persist(
// 3. Immer: enables mutable draft syntax while preserving immutability
immer((set) => ({
theme: 'system',
notifications: { email: true, push: false },
setTheme: (theme) =>
set(
(state) => {
state.theme = theme;
},
false,
'settings/setTheme' // Descriptive action label for DevTools
),
toggleEmailNotifications: () =>
set((state) => {
// Direct structural mutation handled safely via Immer
state.notifications.email = !state.notifications.email;
}),
})),
{
name: 'app_user_settings',
storage: createJSONStorage(() => localStorage),
// Selective persistence: sync only theme, omitting notifications
partialize: (state) => ({ theme: state.theme }),
}
),
{ name: 'SettingsStore' }
)
);
```
## 6. Accessing State Outside React Lifecycles
Because a Zustand store exists outside the React render pipeline, you can read or update state inside non-React files—such as API clients, interceptors, WebSocket handlers, or analytics services—without passing references through props.
```ts
// src/api/httpClient.ts
import axios from 'axios';
import { useAppStore } from '../stores/useAppStore';
export const apiClient = axios.create({ baseURL: '/api' });
// Read state imperatively outside of a React component
apiClient.interceptors.request.use((config) => {
const token = useAppStore.getState().user?.id;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Update state imperatively in response to network events
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
useAppStore.getState().logout(); // Dispatch logout action directly
}
return Promise.reject(error);
}
);
```
## 7. Architectural Boundary: Client State vs. Server Cache
A common mistake in modern React applications is treating Zustand as a general-purpose data-fetching store.
Server responses belong in a dedicated caching layer, while Zustand manages synchronous client state.
| Dimension | Server State | Client State | Characteristics |
| --- | --- | --- | --- |
| Asynchronous, remote, shared, requires deduplication, background re-validation, and cache invalidation. | Synchronous, local, immediate, ephemeral or session-based. | Examples | User profiles, catalog items, paginated search results, order records. |
| UI toggles, modal queues, form wizards, volume/playback controls. | Recommended Tool | TanStack Query (React Query) / SWR | Zustand |
```text
┌────────────────────────┐
│ Application State Flow │
└───────────┬────────────┘
│
┌────────────────┴────────────────┐
▼ ▼
Remote Data? Local UI Data?
(API responses, cache) (Theme, Modals, Drawer)
│ │
▼ ▼
TanStack Query Zustand
```
