useLocalStorage
interact with localStorage
We want to read localStorage, and/or persist a value in it.
We interact with localStorage with a getter and a setter, in a fashion similar to React's useState API:
const [foo, setFoo, removeEntry] = useLocalStorage<AiModel>(config)
removeEntry() aims to clear localStorage.
We must provide a config, with the local storage key. We can also provide an initial/fallback value to set when the localStorage is missing a value:
const config = {
key: "ai-provider",
defaultValue: "GPT",
}
synchronous version (opt-in)
In the synchronous version, the hook reads local storage before the first render. If the entry is missing, it creates one with defaultValue, and initialize state with it:
const config = {
// synchronous version
getInitialValueInEffect: false,
}
asynchronous version (default)
In the asynchronous version, the hook initializes state with the default value. The localStorage lookup runs later, as an effect, after the first paint, avoiding delay. Only then is the state changed to that value.
Having the first paint ignoring the persisted value is not always desirable.