# useLocalStorage > State persisted to localStorage. - Category: State - Package: `hookli` (install with `npm i hookli`) - Docs: https://hookli.vercel.app/docs/use-local-storage ## Signature ```ts useLocalStorage(key: string, initialValue: T): { value: T; setStoredValue: (value: T | ((val: T) => T)) => void } ``` ## Parameters - `key`: `string` — The localStorage key to read and write. - `initialValue`: `T` — Value used before hydration and when the key is empty. Prefer a stable reference — the sync effect depends on it. ## Returns - `value`: `T` — The stored value. Server-rendered as initialValue, then synced from localStorage after mount. - `setStoredValue`: `(value: T | ((val: T) => T)) => void` — Persists to localStorage and updates state; accepts a value or an updater function. ## Usage ```tsx import { useLocalStorage } from "hookli"; export function Demo() { const { value, setStoredValue } = useLocalStorage("note", ""); return (
setStoredValue(e.target.value)} />
); } ``` ## Source `src/hooks/useLocalStorage.hook.ts` ```ts import { useEffect, useState } from "react"; export const useLocalStorage = (key: string, initialValue: T) => { const [value, setValue] = useState(initialValue); useEffect(() => { const item = window.localStorage.getItem(key); const parsedValue = item ? JSON.parse(item) : initialValue; setValue(parsedValue); }, [key, initialValue]); const setStoredValue = (newValue: T | ((val: T) => T)) => { const updatedValue = newValue instanceof Function ? newValue(value) : newValue; window.localStorage.setItem(key, JSON.stringify(updatedValue)); setValue(updatedValue); }; return { value, setStoredValue }; }; ```