wkkkis-hooks

use-local-storage (use-local-storage)

Manages local storage with declarative methods.

v0.1.0

Usage

import { use-local-storage } from "@/hooks"
1"use client"; 2 3import React from "react"; 4 5import { 6 Card, 7 CardContent, 8 CardDescription, 9 CardFooter, 10 CardHeader, 11 CardTitle, 12} from "@/components/ui/card"; 13import { Input } from "@/components/ui/input"; 14import { Label } from "@/components/ui/label"; 15 16import { useLocalStorage } from "@/components/hooks/use-local-storage"; 17 18export function UseLocalStorageDemo() { 19 // Example with a string 20 const [name, setName] = useLocalStorage<string>("demo-name", ""); 21 22 return ( 23 <Card className="relative max-w-sm w-full"> 24 <CardHeader> 25 <CardTitle>useLocalStorage</CardTitle> 26 <CardDescription> 27 This component uses the <code>useLocalStorage</code> hook to manage a 28 local storage item. 29 </CardDescription> 30 </CardHeader> 31 <CardContent className="space-y-6"> 32 <div className="flex flex-col gap-2"> 33 <Label htmlFor="name">Name</Label> 34 <Input 35 id="name" 36 value={name} 37 onChange={(e) => setName(e.target.value)} 38 placeholder="Enter your name" 39 /> 40 </div> 41 <div className="flex items-end gap-2"> 42 <p>Name:</p> 43 <pre className="text-sm text-muted-foreground bg-accent w-fit px-1 py-0.5 rounded-xs"> 44 {name} 45 </pre> 46 </div> 47 </CardContent> 48 <CardFooter> 49 <p className="text-muted-foreground text-sm"> 50 Looks in the local storage for the key <code>demo-name</code>. 51 </p> 52 </CardFooter> 53 </Card> 54 ); 55} 56

Install

npx wkkkis-hooks add use-local-storage

Options

NameTypeDefaultDescription
keystring-The key to store the value in local storage
initialValuestring-The initial value to store in local storage
options?UseLocalStorageOptions-The options for the hook

Cross-Tab Synchronization

  • The hook listens for storage events and updates the state if the value changes in another tab or window.

Serialization & Deserialization

  • By default, values are serialized with JSON.stringify and deserialized with JSON.parse .
  • You can provide custom serialize and deserialize functions for non-JSON data or advanced use cases.

Error Handling

  • If reading or writing to localStorage fails (e.g., quota exceeded, invalid JSON), the hook logs a warning and falls back to the initial value.

SSR & Initial Value

  • On the server, the hook always returns the initial value.
  • The initial value is only used if there is no value in localStorage for the given key.

Best Practices & Caveats

  • The hook is client-side only; on the server, it does not interact with localStorage.
  • Avoid storing sensitive data in localStorage.
  • Changing the key will re-read and update the value from localStorage.
  • For best performance, avoid creating new serialize / deserialize functions on every render (use useCallback or useMemo if needed).

Files in this hook

SourceDestination
files/use-local-storage.tssrc/hooks/use-local-storage.ts