storage-react-hook
v0.1.0
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. Additionally there is a useSerializer() helper which allows storing more than simple strings.
Features
useLocalStorage()anduseSessionStorage()hooks.- State-like API:
[value, setValue] = useLocalStorage(key). - 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. - 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>
</>
);
}Updating from the previous value
import { useLocalStorage } from 'storage-react-hook';
function Counter() {
const [count, setCount] = useLocalStorage('count');
return (
<button
onClick={() => {
setCount((previous) => String(Number(previous ?? 0) + 1));
}}
>
Count: {count ?? '0'}
</button>
);
}API
useLocalStorage(key)
Reads and writes a string value from window.localStorage.
const [value, setValue] = useLocalStorage(key);Returns:
readonly [
string | null,
(
value:
| string
| null
| undefined
| ((previous: string | null) => string | null | undefined)
) => void,
]useSessionStorage(key)
Reads and writes a string value from window.sessionStorage.
const [value, setValue] = useSessionStorage(key);Returns the same tuple shape as useLocalStorage().
Removing Values
Passing null or undefined to a setter removes the storage item.
const [value, setValue] = useLocalStorage('draft');
setValue(null);
setValue(undefined);Notes
- This package is intended for browser environments.
useLocalStorage()anduseSessionStorage()store raw strings.- Storage read/write errors are handled safely, so restricted storage access should not crash your component.
Working With JSON Values
The main hooks store strings, just like the Web Storage API. If you want to work with objects, arrays, numbers, booleans, or other JSON-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 [jsonValue, setJsonValue] = 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'));If the stored value is missing, jsonValue is undefined. Parse and stringify errors are not swallowed, so custom serializers should handle invalid input if that is expected.
Passing null or undefined through the serializer setter also removes the storage item:
const [storedValue, setStoredValue] = useLocalStorage('settings');
const [settings, setSettings] = useSerializer<Settings>(storedValue, setStoredValue);
setSettings(null);
setSettings(undefined);By default, useSerializer() uses JSON.parse() and JSON.stringify(), but both functions can be replaced with an options object:
const [value, setValue] = useSerializer(
storedValue,
setStoredValue,
{
parse: value => Number(value),
stringify: value => String(value),
},
);License
MIT
