npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

storage-react-hook

v0.1.1

Published

React hooks for localStorage and sessionStorage with a useState-like API.

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() and useSessionStorage() 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 storage events from other tabs/windows.
  • Removes the storage item when the next value is null or undefined.
  • 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-hook

Usage

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') === null

Updating 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 | null

When a string default value is provided, the returned value is always a string:

const [value, setValue] = useLocalStorage('key', 'default');
// value: string

The 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: Settings

Without a default value:

const [settings] = useSerializer<Settings>(
	...useLocalStorage('settings'),
);

// settings: Settings | undefined

Like 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') === null

Updater 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: number

Parse 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() and useSessionStorage() store raw strings.
  • Default values are fallbacks and are not automatically written to storage.
  • useSerializer() defaults are provided as deserialized values of type T, 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