kitzo

React utilities library

useLocalStorage

Persist state to the browser's localStorage. Syncs state across multiple tabs.

Usage

LocalStorage.tsx
const [value, setValue] = useLocalStorage('key', 'initialValue');

Example

Saved value:

Try refreshing the page, the state is persisted!

ThemeToggle.tsx
import { useLocalStorage } from 'kitzo';
            
function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle Theme: {theme}
    </button>
  );
}

API

ParameterTypeDescription
key
string

The localStorage key to store the value under

initialValue
any

The initial value to use if no value exists in localStorage

options.debounceMs
number

Delay in ms to debounce writes to localStorage (default: 0)

options.onMount
function

Callback that runs when the initial value is read from localStorage

Returns an array containing the current state value and a setter function, similar to useState.

Behavior

  • Syncs changes to localStorage automatically.
  • Listens to storage events, syncing state across browser tabs.
  • Safely handles hydration issues during server-side rendering.
  • Supports debouncing writes with the debounceMs option.