useLocalStorage
useLocalStorage
exposes an API similar to useState
, but uses the local storage as a single source of truth. It requires a key
that describes the local storage entry, and a defaultValue
for when such entry is missing.
const config = {
key: "default-ai-provider",
defaultValue: "GPT",
}
synchronous version (opt-in)
When the component mounts, the hook attempts to read a persisted value from the local storage, and initializes the state with it. If the entry is missing, it creates one with defaultValue
, and initialize the state with it.
const config = {
// ..
// opt-in for the synchronous version
getInitialValueInEffect: false,
}
asynchronous version (default)
In the asynchronous version, the hook immediately initializes the state with the default value, to avoid delaying the first paint. The local storage lookup is implemented as an effect that runs later on, after the first paint. Only then it may push the persisted value to the state.
Having the first paint ignoring the persisted value is not always desirable, that's why we may opt-in for the synchronous version.
exposed API
The hook exposes the state value and the dispatch method. It also exposes a method to remove the entry.
const [provider, setProvider, removeEntry] = useLocalStorage<AIProvider>(config)
The hook listens for changes in state and updates the local storage accordingly.