# Middleware & Persist

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

Subject: State Management | Lesson 9 of 22 | 5 min read
Interactive lesson: https://codewithanimation.in/state-management/zustand-middleware-and-persist
Previous: [Transient Updates](https://codewithanimation.in/state-management/zustand-transient-updates.md) | Next: [The Redux Mental Model](https://codewithanimation.in/state-management/redux-mental-model.md)

## 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' }
  )
);
```

## Common mistake: Next.js Hydration Mismatches

If you are using Server-Side Rendering (SSR) with Next.js, persisted state can cause hydration errors. The server renders the initial HTML with the default state (e.g., `bears: 0`), but the client immediately hydrates with the persisted state from `localStorage` (e.g., `bears: 5`). To fix this, you must render a fallback UI on the first pass, or wait until the component has mounted before rendering the persisted data.

## Tip: Partial Persistence

You don't have to save *everything* in the store. The `persist` config object accepts a `partialize` function, allowing you to pick and choose exactly which state properties should be saved to `localStorage`, ignoring transient UI state.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/state-management/zustand-middleware-and-persist

## Check yourself

### Question 1

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

- A. It connects your Zustand store to a backend database.
- B. It automatically saves and loads state from browser storage (like localStorage) to survive page reloads.
- C. It prevents hydration mismatches in Next.js automatically.

Correct answer: B

The `persist` middleware handles the JSON serialization/deserialization and syncs your store with `localStorage` or `sessionStorage` automatically.

- Why not A: It persists to client-side storage, not a backend.
- Why not C: It actually *causes* hydration mismatches if not handled properly. You still have to manage hydration yourself.

## 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.
