ReactError Fix2026 Updated

React State Not Persisting on Refresh— Fixed [2026]

Also covers: localStorage · sessionStorage · Zustand persist · URL state

January 20266 min readReact 18 · Next.js

⚡ Quick Fix — Persist to localStorage

component.jsx
const [theme, setTheme] = useState(
  () => localStorage.getItem('theme') ?? 'light'  // read on init
)

useEffect(() => {
  localStorage.setItem('theme', theme)  // write on change
}, [theme])

Why React State Resets on Refresh

React state lives in JavaScript memory. When you refresh the page, the browser clears all memory and starts the JavaScript engine fresh. useState always starts with its initial value on a fresh page load. To keep data across refreshes, you need to save it somewhere permanent.

1

Persist to localStorage

Survives refresh and browser close
2 min
components/ThemeToggle.jsx
import { useState, useEffect } from 'react'

export default function ThemeToggle() {
  const [theme, setTheme] = useState(() => {
    // ✅ Lazy initializer — read from localStorage on first render
    // Safe check for SSR (Next.js)
    if (typeof window === 'undefined') return 'light'
    return localStorage.getItem('theme') ?? 'light'
  })

  useEffect(() => {
    // ✅ Write to localStorage whenever theme changes
    localStorage.setItem('theme', theme)
    document.documentElement.dataset.theme = theme
  }, [theme])

  return (
    <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
      Theme: {theme}
    </button>
  )
}
2

Custom useLocalStorage Hook

Reusable — one line to persist any state
3 min
hooks/useLocalStorage.js
import { useState, useEffect } from 'react'

export function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    if (typeof window === 'undefined') return initialValue
    try {
      const stored = localStorage.getItem(key)
      return stored !== null ? JSON.parse(stored) : initialValue
    } catch {
      return initialValue
    }
  })

  useEffect(() => {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (err) {
      console.warn('localStorage write failed:', err)
    }
  }, [key, value])

  return [value, setValue]
}

// Usage — exactly like useState, but persists
function Settings() {
  const [theme,    setTheme]    = useLocalStorage('theme', 'light')
  const [language, setLanguage] = useLocalStorage('lang', 'en')
  const [cart,     setCart]     = useLocalStorage('cart', [])

  return <div>Theme: {theme}</div>
}
3

sessionStorage — Tab Session Only

Cleared when tab closes
1 min
hooks/useSessionStorage.js
import { useState, useEffect } from 'react'

export function useSessionStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    if (typeof window === 'undefined') return initialValue
    const stored = sessionStorage.getItem(key)
    return stored !== null ? JSON.parse(stored) : initialValue
  })

  useEffect(() => {
    sessionStorage.setItem(key, JSON.stringify(value))
  }, [key, value])

  return [value, setValue]
}

// Use case: persist multi-step form data across page navigations
// but clear it when the user closes the tab
function CheckoutFlow() {
  const [step, setStep]         = useSessionStorage('checkout-step', 1)
  const [formData, setFormData] = useSessionStorage('checkout-data', {})
  return <div>Step {step}</div>
}
4

URL State — Shareable and Bookmark-Friendly

For filters, search, pagination
2 min
components/ProductFilter.jsx
'use client'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'

export default function ProductFilter() {
  const router       = useRouter()
  const pathname     = usePathname()
  const searchParams = useSearchParams()

  const category = searchParams.get('category') ?? 'all'
  const page     = Number(searchParams.get('page') ?? '1')

  function updateFilter(key, value) {
    const params = new URLSearchParams(searchParams)
    params.set(key, value)
    router.push(pathname + '?' + params.toString())
    // URL changes → state persists on refresh AND is shareable
  }

  return (
    <div>
      <select value={category} onChange={e => updateFilter('category', e.target.value)}>
        <option value="all">All</option>
        <option value="shoes">Shoes</option>
      </select>
      <p>Page {page}</p>
    </div>
  )
}
5

Zustand With Persist Middleware

Production state management — automatic persistence
3 min
terminal
npm install zustand
stores/useCartStore.js
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

export const useCartStore = create(
  persist(
    (set, get) => ({
      items: [],
      addItem:    (item) => set(s => ({ items: [...s.items, item] })),
      removeItem: (id)   => set(s => ({ items: s.items.filter(i => i.id !== id) })),
      clearCart:  ()     => set({ items: [] }),
      total: () => get().items.reduce((sum, i) => sum + i.price, 0),
    }),
    {
      name: 'cart-storage',                        // localStorage key
      storage: createJSONStorage(() => localStorage),
    }
  )
)

// Usage in any component — automatically persists to localStorage
function CartButton() {
  const { items, addItem } = useCartStore()
  return <button onClick={() => addItem(product)}>Cart ({items.length})</button>
}

Which Storage to Use

Use caseBest option
Theme, language, display preferenceslocalStorage
Multi-step form data (discard on tab close)sessionStorage
Search filters, pagination (shareable link)URL params
Shopping cart, auth token (simple)localStorage or Zustand persist
User data (across devices/browsers)Database (API call)
Auth sessionhttpOnly cookie (via server)

Frequently Asked Questions

Why does React state reset on page refresh?+
React state is stored in memory — it lives only as long as the JavaScript is running. When you refresh, the browser reloads the page and all JavaScript memory is cleared. To persist state, you must save it somewhere outside of memory: localStorage, sessionStorage, a database, or the URL.
How do I persist React state to localStorage?+
Read from localStorage on init: useState(() => JSON.parse(localStorage.getItem('key')) ?? defaultValue). Write to localStorage on change: useEffect(() => { localStorage.setItem('key', JSON.stringify(value)) }, [value]).
What is the difference between localStorage and sessionStorage?+
localStorage persists forever until manually cleared — even after closing the browser. sessionStorage lasts only for the current browser tab session — cleared when the tab is closed. Use localStorage for theme/preferences, sessionStorage for temporary form data.
localStorage is not defined in Next.js — how to fix?+
window and localStorage do not exist on the server. Access them only in useEffect (runs client-side only): useEffect(() => { const saved = localStorage.getItem('theme'); if (saved) setTheme(saved) }, []). Or check: if (typeof window !== 'undefined') { localStorage.getItem(...) }
Should I use localStorage or a database to persist state?+
localStorage for user preferences (theme, language, UI settings) — private to one browser. Database for user data that should sync across devices and browsers. URL params for shareable state (search filters, pagination).
Zustand vs localStorage for persisting state?+
Zustand with the persist middleware combines both — state is managed with Zustand (reactive, easy updates) and automatically synced to localStorage (persistent). It is cleaner than manually managing localStorage with useEffect.

Need Expert Help?

We Build Production-Grade React Apps

Softplix builds full-stack React and Next.js applications. Need help with state management or persistence architecture? We can help.

Talk to an Engineer