A typed React hook for interacting with the Web Storage API, providing automatic JSON serialization and fallback support.
Important
Data is serialized using JSON.stringify(). Ensure your data types are JSON-compatible (avoid using Map, Set, or objects with circular references).
Tip
This hook uses useSyncExternalStore, which automatically synchronizes the state across all components in your application that share the same key.
Note
An internal cache is used to prevent redundant localStorage reads, optimizing performance during frequent re-renders.
Installation
bash
Description
The useLocalStorage provides a clean, typed API for window.localStorage. It automatically handles the conversion between JavaScript objects and JSON strings, preventing common parsing errors. It includes a fallback mechanism for missing keys and a functional update method that allows for state-like modifications to the stored value. The hook is SSR-safe and performs runtime environment checks before execution.
Parameters
Name
Type
Description
key
string
The key under which the data is stored in localStorage.
options.fallback
T
The value to return if the key does not exist or parsing fails.
Return values
Name
Type
Description
value
T
The current value of the key.
remove
() => void
Specifically removes the entry associated with the provided key.
set
(value: T) => void
Serializes and saves the value to localStorage.
update
(updater: (prev) => T) => void
Updates the value using a callback function (similar to setState).