useLocalStorage

Persists and retrieves state from the browser's local storage.

Code

1import { useState, useEffect } from "react"
2
3export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] {
4  const [storedValue, setStoredValue] = useState<T>(() => {
5    if (typeof window === "undefined") {
6      return initialValue
7    }
8    try {
9      const item = window.localStorage.getItem(key)
10      return item ? JSON.parse(item) : initialValue
11    } catch (error) {
12      console.error(error)
13      return initialValue
14    }
15  })
16
17  useEffect(() => {
18    if (typeof window === "undefined") {
19      return
20    }
21    try {
22      window.localStorage.setItem(key, JSON.stringify(storedValue))
23    } catch (error) {
24      console.error(error)
25    }
26  }, [key, storedValue])
27
28  return [storedValue, setStoredValue]
29}

Usage Example

import { useLocalStorage } from "@/hooks/use-local-storage" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" export function LocalStorageExample() { const [name, setName] = useLocalStorage("user-name", "Guest") return ( <div className="space-y-4"> <Label htmlFor="user-name">Your Name (saved in local storage)</Label> <Input id="user-name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <p className="text-sm text-npui-muted-foreground">Hello, {name}!</p> </div> ) }