ImportantData is serialized using JSON.stringify(). Ensure your data types are JSON-compatible (avoid using Map, Set, or objects with circular references).
TipThis hook uses useSyncExternalStore, which automatically synchronizes the state across all components in your application that share the same key.
NoteAn internal cache is used to prevent redundant localStorage reads, optimizing performance during frequent re-renders.
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.
| 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. |
| 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). |