hook-local-storage
v1.0.3
Published
A tiny React hook for state that persists to `localStorage`. Drop-in replacement for `useState` — same `[value, setValue]` shape, but the value survives page refreshes.
Maintainers
Readme
hook-local-storage
A tiny React hook for state that persists to localStorage. Drop-in replacement for useState — same [value, setValue] shape, but the value survives page refreshes.
Full docs & interactive examples: http://bradgaynor.com/hook-local-storage/
Install
npm install hook-local-storageUsage
import useLocalStorage from 'hook-local-storage'
const Counter = () => {
const [count, setCount] = useLocalStorage('count', 0)
return (
<button onClick={() => setCount(count + 1)}>
count: {count}
</button>
)
}Works with any JSON-serializable value (objects, arrays, strings, numbers, booleans) — not just numbers.
API
const [value, setValue] = useLocalStorage(key, initialValue)key— thelocalStoragekey to read from and write to.initialValue— used when nothing is stored yet underkey(or when running server-side, wherelocalStorageisn't available).value— the current value, read fromlocalStorageon mount.setValue(newValue)— updates state and persistsnewValuetolocalStorage.
