storage-react-hook
v0.1.1
Published
React hooks for localStorage and sessionStorage with a useState-like API.
Maintainers
Readme
storage-react-hook
Small React v18+ hooks for reading and writing window.localStorage and window.sessionStorage from React components.
The package focuses on two hooks: useLocalStorage() and useSessionStorage(). Both follow the familiar React.useState() shape: you get the current stored value and a setter function, and the setter also supports updater functions. An optional default value can be provided and is returned when the storage item is missing.
Additionally there is a useSerializer() helper which allows storing more than simple strings. It also supports its own typed default value, so objects, arrays, numbers, booleans, and other serialized values can use a fallback.
Features
useLocalStorage()anduseSessionStorage()hooks.- State-like API:
[value, setValue] = useLocalStorage(key, defaultValue). - Supports optional default values when a storage item is missing.
- Supports updater functions:
setValue(previous => next). - Keeps components in the same tab in sync when the same storage key changes.
- Reacts to browser
storageevents from other tabs/windows. - Removes the storage item when the next value is
nullorundefined. useSerializer()for objects, arrays, numbers, booleans, and other serialized values.useSerializer()supports typed default values.- Built on React's
useSyncExternalStore.
Installation
npm install storage-react-hookUsage
Raw string storage
import { useLocalStorage, useSessionStorage } from 'storage-react-hook';
function Example() {
const [name, setName] = useLocalStorage('name', '');
const [tabId, setTabId] = useSessionStorage('tab-id');
return (
<>
<input
value={name}
onChange={(event) => setName(event.target.value)}
/>
<button onClick={() => setName(null)}>
Clear name
</button>
<p>Current tab id: {tabId ?? 'not set'}</p>
</>
);
}The default value is only used as a fallback when the storage item is missing. It is not automatically written to storage.
const [theme] = useLocalStorage('theme', 'system');
// If "theme" is not stored:
// theme === 'system'
// localStorage.getItem('theme') === nullUpdating from the previous value
Updater functions receive the effective current value, including the default value when the storage item is missing.
import { useLocalStorage } from 'storage-react-hook';
function Counter() {
const [count, setCount] = useLocalStorage('count', '0');
return (
<button
onClick={() => {
setCount((previous) => String(Number(previous) + 1));
}}
>
Count: {count}
</button>
);
}API
useLocalStorage(key, defaultValue?)
Reads and writes a string value from window.localStorage.
const [value, setValue] = useLocalStorage(key);
const [value, setValue] = useLocalStorage(key, defaultValue);Without a default value, the stored value is string | null:
const [value, setValue] = useLocalStorage('key');
// value: string | nullWhen a string default value is provided, the returned value is always a string:
const [value, setValue] = useLocalStorage('key', 'default');
// value: stringThe default value is returned when the storage item is missing. It is not automatically written to storage.
Returns without a default value:
readonly [
string | null,
(
value:
| string
| null
| undefined
| ((previous: string | null) => string | null | undefined)
) => void,
]Returns with a string default value:
readonly [
string,
(
value:
| string
| null
| undefined
| ((previous: string) => string | null | undefined)
) => void,
]useSessionStorage(key, defaultValue?)
Reads and writes a string value from window.sessionStorage.
const [value, setValue] = useSessionStorage(key);
const [value, setValue] = useSessionStorage(key, defaultValue);It has the same default value behavior and tuple shapes as useLocalStorage().
Removing Values
Passing null or undefined to a setter removes the storage item.
const [value, setValue] = useLocalStorage('draft');
setValue(null);
setValue(undefined);When a default value is provided, removing the stored item causes the hook to return the default value again.
const [value, setValue] = useLocalStorage('theme', 'system');
setValue('dark');
// value === 'dark'
setValue(null);
// storage item is removed
// value === 'system'The default value is still only a fallback and is not written back automatically.
Working With Serialized Values
The main storage hooks store raw strings, just like the Web Storage API. If you want to work with objects, arrays, numbers, booleans, or other serializable values, the package also includes useSerializer().
import { useLocalStorage, useSerializer } from 'storage-react-hook';
type Settings = {
theme: 'light' | 'dark';
showHints: boolean;
};
function SettingsPanel() {
const [storedSettings, setStoredSettings] = useLocalStorage('settings');
const [settings, setSettings] = useSerializer<Settings>(
storedSettings,
setStoredSettings,
);
return (
<button
onClick={() => {
setSettings((previous) => ({
showHints: previous?.showHints ?? true,
theme: previous?.theme === 'dark' ? 'light' : 'dark',
}));
}}
>
Current theme: {settings?.theme ?? 'light'}
</button>
);
}useSerializer() parses the stored string with JSON.parse() and converts updates back with JSON.stringify().
const [serializedValue, setSerializedValue] = useSerializer<T>(
value,
setValue,
options,
);Since useLocalStorage() and useSessionStorage() return the expected [value, setValue] pair, you can also pass them directly with spread syntax:
const [value, setValue] = useSerializer(
...useLocalStorage('storage-key'),
);Serializer default values
useSerializer() supports a typed defaultValue through its options object.
const [settings, setSettings] = useSerializer<Settings>(
...useLocalStorage('settings'),
{
defaultValue: {
theme: 'light',
showHints: true,
},
},
);When a serializer default value is provided, the returned value is T instead of T | undefined.
const [settings] = useSerializer<Settings>(
...useLocalStorage('settings'),
{
defaultValue: {
theme: 'light',
showHints: true,
},
},
);
// settings: SettingsWithout a default value:
const [settings] = useSerializer<Settings>(
...useLocalStorage('settings'),
);
// settings: Settings | undefinedLike storage defaults, serializer defaults are fallback values only. They are not automatically written to storage.
const [settings] = useSerializer<Settings>(
...useLocalStorage('settings'),
{
defaultValue: {
theme: 'light',
showHints: true,
},
},
);
// If "settings" is not stored:
// settings === { theme: 'light', showHints: true }
// localStorage.getItem('settings') === nullUpdater functions also receive the effective value, including the serializer default when the stored value is missing.
const [settings, setSettings] = useSerializer<Settings>(
...useLocalStorage('settings'),
{
defaultValue: {
theme: 'light',
showHints: true,
},
},
);
setSettings((previous) => ({
...previous,
theme: previous.theme === 'dark' ? 'light' : 'dark',
}));In this example, previous is typed as Settings, because a default value is guaranteed.
Without a default value, updater functions receive T | undefined:
const [settings, setSettings] = useSerializer<Settings>(
...useLocalStorage('settings'),
);
setSettings((previous) => ({
showHints: previous?.showHints ?? true,
theme: previous?.theme === 'dark' ? 'light' : 'dark',
}));Removing serialized values
Passing null or undefined through the serializer setter removes the underlying storage item.
const [settings, setSettings] = useSerializer<Settings>(
...useLocalStorage('settings'),
);
setSettings(null);
setSettings(undefined);When a serializer default value is configured, removing the stored value causes the default value to be returned again.
const [settings, setSettings] = useSerializer<Settings>(
...useLocalStorage('settings'),
{
defaultValue: {
theme: 'light',
showHints: true,
},
},
);
setSettings({
theme: 'dark',
showHints: false,
});
setSettings(null);
// localStorage.getItem('settings') === null
// and settings variable falls back to:
// { theme: 'light', showHints: true }Custom serializers
By default, useSerializer() uses JSON.parse() and JSON.stringify(), but both functions can be replaced with an options object.
const [value, setValue] = useSerializer<number>(
storedValue,
setStoredValue,
{
parse: value => Number(value),
stringify: value => String(value),
},
);A custom serializer can be combined with a default value:
const [value, setValue] = useSerializer<number>(
storedValue,
setStoredValue,
{
defaultValue: 0,
parse: value => Number(value),
stringify: value => String(value),
},
);
// value: numberParse and stringify errors are not swallowed, so custom serializers should handle invalid input if that is expected.
Notes
- This package is intended for browser environments.
useLocalStorage()anduseSessionStorage()store raw strings.- Default values are fallbacks and are not automatically written to storage.
useSerializer()defaults are provided as deserialized values of typeT, so they do not need to be manually stringified.- Storage read/write errors are handled safely, so restricted storage access should not crash your component.
License
MIT
