Back to Snippets
ReactTypeScript

React useLocalStorage Hook

A custom hook that persists state to localStorage with automatic serialization.

reacthooklocalStoragestate
import { useState, useEffect } from class=class="text-emerald-400">"text-emerald-400">'react'

function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch {
      return initialValue
    }
  })

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue))
    } catch {
      console.error(class=class="text-emerald-400">"text-emerald-400">'Failed to save to localStorage')
    }
  }, [key, storedValue])

  return [storedValue, setStoredValue]
}

export default useLocalStorage

How to Use

Import and use like useState: const [name, setName] = useLocalStorage('user-name', 'Guest'). The value persists across page reloads automatically.

Related Technology

React

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call