Persist Middleware: Local Storage Integration
You'll learn how to automatically save your Zustand store to browser storage so state survives page refreshes.
When users refresh the page, your entire React state normally vanishes—back to square one. For things like user preferences, shopping carts, or form drafts, this creates a frustrating experience. Zustand's persist() middleware solves this by automatically syncing your store with localStorage (or sessionStorage), making your state durable across browser sessions.
The Core Idea
Think of persist() as an auto-save feature for your game. Every time your state changes, it quietly writes to the save file. When the game restarts (page refresh), it loads from that file instead of starting over.
Without persist, you'd need to manually call localStorage.setItem() in every action and localStorage.getItem() on initialization—tedious and error-prone.
How It Works
Wrap your store creator with the persist() middleware:
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
const useStore = create(
persist(
(set) => ({
theme: 'light',
cart: [],
setTheme: (theme) => set({ theme }),
addToCart: (item) => set((state) => ({
cart: [...state.cart, item]
})),
}),
{
name: 'my-app-storage', // unique localStorage key
}
)
);
Now theme and cart automatically save to localStorage under the key 'my-app-storage'. When the component mounts, Zustand reads that key and restores the state. Your components use the store exactly as before—no extra code needed.
When to Use It
Perfect for user preferences (theme, language), authentication tokens, shopping carts, or any state that should feel "permanent" from the user's perspective.
Key Takeaway: Zustand's persist() middleware eliminates boilerplate by automatically synchronizing store state with browser storage, making your app state survive refreshes without manual save/load logic.