useLocalStorage

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

NameTypeDescription
keystringThe key under which the data is stored in localStorage.
options.fallbackTThe value to return if the key does not exist or parsing fails.

Return values

NameTypeDescription
valueTThe current value of the key.
remove() => voidSpecifically removes the entry associated with the provided key.
set(value: T) => voidSerializes and saves the value to localStorage.
update(updater: (prev) => T) => voidUpdates the value using a callback function (similar to setState).

Demo

This component is loading.

Source code

tsx