Middleware & Persist

Enhance your store with middleware to easily save state to local storage.

State Management5 min readConcept 9 of 22

What is Zustand Middleware?

Zustand allows you to wrap your store's create function with 'middleware'. Middleware sits between your action calls and the actual state update, allowing you to intercept, modify, or log state changes.

The most popular built-in middleware is persist, which automatically saves your store's state to the browser's localStorage (or sessionStorage) and rehydrates it when the page loads.

The Persistence Problem

If you've ever tried to persist React state, you know the struggle: writing custom useEffect hooks, parsing JSON on initial render, and dealing with Hydration mismatches in Next.js.

Zustand's persist middleware handles all of this automatically. You wrap your store once, and your state instantly survives page reloads.

Using the `persist` Middleware

To use it, import persist from zustand/middleware and wrap your store definition. You must provide a unique name which will be used as the key in localStorage.

tsx import { create } from 'zustand'; import { persist } from 'zustand/middleware'; export const useThemeStore = create( persist( (set) => ({ mode: 'light', toggle: () => set((s) => ({ mode: s.mode === 'light' ? 'dark' : 'light' })), }), { name: 'theme-storage' } ) );

Local Storage Simulator

Modify the state using the toolbar, then click the 'Reload Page' button. Notice how the persisted state is instantly restored from the simulated localStorage.

import { create } from 'zustand'; import { persist } from 'zustand/middleware'; export const useThemeStore = create( persist( (set) => ({ theme: 'light', toggle: () => set((s) => ({ theme: s.theme === 'light' ? 'dark' : 'light' })), }), { name: 'theme-storage' } ) );
React UI
☀️
"light"
localStorage

"theme-storage"

{"state":{"theme":"light"}}

Click toggleTheme() to update state AND sync it to localStorage. Click Simulate Reload to watch the component unmount and immediately rehydrate from storage.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary benefit of the Zustand `persist` middleware?

Remember this

  • Middleware wraps your create function to extend its capabilities.
  • The persist middleware automatically syncs state to browser storage.
  • You must provide a unique name config option for the storage key.
  • Be careful with hydration mismatches when using persistence with Next.js SSR.

Done with this concept?

Mark it complete to track your progress. No login needed.