State
useLocalStorage
State persisted to localStorage (MDN, opens in a new tab).
Demo
live · imported from hookli
Stored under hookli-docs-note — it survives a reload.
import { useLocalStorage } from "hookli";
export function Demo() {
const { value, setStoredValue } = useLocalStorage("note", "");
return (
<div>
<input value={value} onChange={(e) => setStoredValue(e.target.value)} />
<button type="button" onClick={() => setStoredValue("")}>Clear</button>
</div>
);
}Usage
import { useLocalStorage } from "hookli";
export function Demo() {
const { value, setStoredValue } = useLocalStorage("note", "");
return (
<div>
<input value={value} onChange={(e) => setStoredValue(e.target.value)} />
<button type="button" onClick={() => setStoredValue("")}>Clear</button>
</div>
);
}API
useLocalStorage<T>(key: string, initialValue: T): { value: T; setStoredValue: (value: T | ((val: T) => T)) => void }Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| 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
| Name | Type | Description |
|---|---|---|
| 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. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useEffect, useState } from "react";
export const useLocalStorage = <T>(key: string, initialValue: T) => {
const [value, setValue] = useState<T>(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 };
};