Efe

Efe

SOULTEL

Full-Stack Developer & Open Source Enthusiast

Back to Snippets
TYPESCRIPTJanuary 15, 2024
React

useLocalStorage Hook

Persist React state in localStorage

ReactTypeScriptHookslocalStorageState Management

TYPESCRIPT
import { useState, useEffect } from 'react'

export function useLocalStorage(key: string, initialValue: T) {
  const [value, setValue] = useState(() => {
    if (typeof window === 'undefined') return initialValue

    try {
      const item = window.localStorage.getItem(key)
      return item ? JSON.parse(item) : initialValue
    } catch {
      return initialValue
    }
  })

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

  return [value, setValue] as const
}

Usage

TYPESCRIPT
// Theme toggle
const [theme, setTheme] = useLocalStorage('theme', 'light')

// User preferences
const [user, setUser] = useLocalStorage('user', { name: '', email: '' })

// Shopping cart
const [cart, setCart] = useLocalStorage('cart', [])