ZustandPersistError Fix2026 Updated

Zustand Persist Not Working— localStorage Not Saving [Fixed 2026]

Also covers: correct persist setup · SSR hydration flash · partialize · version migration · sessionStorage

January 20266 min readZustand v4/v5 · Next.js · TypeScript

⚡ The Problem

Error
// State resets on page refresh — persist not saving to localStorage
// OR: localStorage key exists but state doesn't restore
// OR: SSR hydration flash — default values flash before persisted values load

✅ Correct persist setup

Correct persist middleware structure
import { create } from "zustand"
import { persist, createJSONStorage } from "zustand/middleware"

const useStore = create(
  persist(                          // ← persist wraps the store creator
    (set) => ({
      count: 0,
      increment: () => set(s => ({ count: s.count + 1 })),
    }),
    {
      name: "my-app-store",         // ← required: localStorage key name
      storage: createJSONStorage(() => localStorage),
    }
  )
)

Why Zustand Persist Doesn't Save to localStorage

The persist middleware wraps the store creator function and intercepts set() calls to write state to storage. Three things can silently prevent it from working: incorrect wrapping order, a missing name option, or non-serializable values in state (functions, Dates, Map/Set) that JSON.stringify converts to null or drops entirely.

1

Correct persist Middleware Setup

State resets on refresh — persist silently not working
3 min
Complete TypeScript persist store
import { create } from "zustand"
import { persist, createJSONStorage } from "zustand/middleware"

interface SettingsStore {
  theme: "light" | "dark" | "system"
  language: string
  sidebarOpen: boolean
  setTheme: (theme: "light" | "dark" | "system") => void
  setLanguage: (lang: string) => void
  toggleSidebar: () => void
}

export const useSettingsStore = create<SettingsStore>()(
  persist(
    (set) => ({
      // Initial / default values
      theme: "system",
      language: "en",
      sidebarOpen: true,

      setTheme: (theme) => set({ theme }),
      setLanguage: (language) => set({ language }),
      toggleSidebar: () => set(s => ({ sidebarOpen: !s.sidebarOpen })),
    }),
    {
      name: "settings-store",                           // ← localStorage key
      storage: createJSONStorage(() => localStorage),   // ← explicit storage
    }
  )
)

// Verify it works — check localStorage in DevTools:
// Application → Local Storage → http://localhost:3000 → "settings-store"
// Should contain: { "state": { "theme": "system", ... }, "version": 0 }

After setting up persist, open DevTools → Application → Local Storage to confirm the key is being written. If the key is absent, the middleware is not running — check the wrapping order.

2

Fix SSR Hydration Flash in Next.js

Default values flash before persisted values load
4 min

On SSR, the store initializes with defaults. On the client, persist hydrates from localStorage asynchronously — causing a visible flash. Guard components until hydration is complete.

useHydration hook — wait for persist to load
"use client"

import { useEffect, useState } from "react"
import { useSettingsStore } from "@/stores/settings"

// Hook to check if persist has hydrated
function useHydration() {
  const [hydrated, setHydrated] = useState(false)

  useEffect(() => {
    // hasHydrated is true once persist has loaded localStorage data
    const unsubHydrate = useSettingsStore.persist.onHydrate(() => {})
    const unsubFinish = useSettingsStore.persist.onFinishHydration(() => {
      setHydrated(true)
    })

    // If already hydrated (fast path)
    if (useSettingsStore.persist.hasHydrated()) setHydrated(true)

    return () => {
      unsubHydrate()
      unsubFinish()
    }
  }, [])

  return hydrated
}

// Use in components that depend on persisted state
function ThemeToggle() {
  const hydrated = useHydration()
  const { theme, setTheme } = useSettingsStore()

  // Show skeleton until localStorage has loaded
  if (!hydrated) return <div className="w-8 h-8 bg-gray-200 rounded animate-pulse" />

  return (
    <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
      {theme === "dark" ? "🌙" : "☀️"}
    </button>
  )
}
3

Use partialize to Exclude Non-Serializable State

Functions and non-serializable values breaking persist
3 min

Actions (functions) and non-serializable types like Date , Map , Set cannot be JSON-serialized. Use partialize to persist only the serializable data fields.

partialize — persist only selected fields
interface CartStore {
  items: CartItem[]
  couponCode: string | null
  isLoading: boolean          // ← don't persist (volatile)
  lastUpdated: Date           // ← don't persist (not serializable as-is)
  addItem: (item: CartItem) => void    // ← don't persist (function)
  removeItem: (id: string) => void     // ← don't persist (function)
}

const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      items: [],
      couponCode: null,
      isLoading: false,
      lastUpdated: new Date(),
      addItem: (item) => set(s => ({ items: [...s.items, item] })),
      removeItem: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
    }),
    {
      name: "cart-store",
      storage: createJSONStorage(() => localStorage),

      // ✅ Only persist items and coupon — exclude functions, loading, Date
      partialize: (state) => ({
        items: state.items,
        couponCode: state.couponCode,
      }),
    }
  )
)
4

Handle Schema Changes with Version Migration

Updated store shape breaks old persisted data
4 min

When you change the structure of persisted state, old data in localStorage may be incompatible. Use version and migrate to transform old data to the new shape.

version + migrate — handle breaking changes
const useUserStore = create<UserStore>()(
  persist(
    (set) => ({
      // v2 shape — user object instead of flat fields
      user: null as User | null,
      preferences: { theme: "system", lang: "en" },
      setUser: (user) => set({ user }),
    }),
    {
      name: "user-store",
      version: 2,   // ← bump this when you change the persisted state shape

      migrate: (persistedState: any, version: number) => {
        // v0 → v1: renamed 'username' to 'name'
        if (version === 0) {
          persistedState.name = persistedState.username
          delete persistedState.username
        }

        // v1 → v2: moved flat fields into user object
        if (version <= 1) {
          persistedState.user = {
            name: persistedState.name,
            email: persistedState.email,
          }
          delete persistedState.name
          delete persistedState.email
        }

        return persistedState
      },
    }
  )
)

Increment the version number every time you change the persisted state shape. Without migration, users with old localStorage data may see corrupted state or runtime errors when the old shape doesn't match your new store structure.

5

Use sessionStorage or Custom Storage

Want storage that clears on tab close
2 min
sessionStorage and custom storage options
import { persist, createJSONStorage } from "zustand/middleware"

// ✅ sessionStorage — clears when browser tab closes
const useWizardStore = create()(
  persist(
    (set) => ({
      step: 1,
      formData: {},
      nextStep: () => set(s => ({ step: s.step + 1 })),
    }),
    {
      name: "wizard-store",
      storage: createJSONStorage(() => sessionStorage),   // ← sessionStorage
    }
  )
)

// ✅ Custom storage — e.g. IndexedDB via idb-keyval
import { get, set, del } from "idb-keyval"

const idbStorage = {
  getItem: async (name: string) => {
    return (await get(name)) ?? null
  },
  setItem: async (name: string, value: string) => {
    await set(name, value)
  },
  removeItem: async (name: string) => {
    await del(name)
  },
}

const useLargeDataStore = create()(
  persist(
    (set) => ({ data: [] }),
    {
      name: "large-data-store",
      storage: createJSONStorage(() => idbStorage),   // ← IndexedDB for large data
    }
  )
)

// ✅ Clear persisted storage:
useWizardStore.persist.clearStorage()
// or:
localStorage.removeItem("wizard-store")

Prevention

Frequently Asked Questions

Why is Zustand persist not saving to localStorage?+
The most common cause is wrapping the store creator incorrectly. persist() must wrap the inner function — create(persist(fn, options)) — not the other way around. Also ensure you have a unique name option — this is the localStorage key. Missing the name causes persist to silently fail.
Why does my Zustand persisted state flash on page load in Next.js?+
Zustand's persist middleware reads localStorage asynchronously after hydration. During SSR, the store initializes with default values. On the client, it then hydrates from localStorage — causing a brief flash where the UI shows defaults before showing persisted values. Fix this by checking useStore.persist.hasHydrated() and showing a skeleton until hydration completes.
What is partialize in Zustand persist?+
partialize lets you select which parts of your store to persist. By default, persist saves the entire store state. Use partialize to exclude actions (functions), non-serializable values like Date objects or Map/Set, sensitive data like auth tokens, or volatile state like loading flags.
What happens to persisted state when I add new fields to my Zustand store?+
The persisted state in localStorage is merged with your store's initial state on hydration. New fields that don't exist in localStorage will use the initial state defaults. Removed fields in localStorage are ignored. If you change the shape of existing fields, use the version option with a migrate function to transform old data.
Can I use Zustand persist with sessionStorage instead of localStorage?+
Yes. Pass a custom storage option to persist: storage: createJSONStorage(() => sessionStorage). sessionStorage clears when the browser tab is closed, unlike localStorage which persists indefinitely. Use it for temporary session data like current wizard step or unsaved draft state.
How do I clear Zustand persisted state?+
Call useStore.persist.clearStorage() to remove the persisted data from localStorage. Or call localStorage.removeItem(storeName) directly with your store's name. To reset the store to initial state, also call useStore.setState(initialState) after clearing.

Need Expert Help?

We Build React Apps with Zustand

Softplix engineers architect Zustand stores with persist, migrations, and SSR-safe hydration for production Next.js apps. Let us help.

Talk to an Engineer