Piplup
@piplup/utilsHooks

useLocalStorage

Reactive hook that reads a localStorage key and re-renders when it changes.

useLocalStorage returns the current string value of a localStorage key and re-renders when that key changes. It is read-only: write with setItem and removeItem, also exported from @piplup/utils.

import { removeItem, setItem, useLocalStorage } from "@piplup/utils";

function ThemeToggle() {
  const theme = useLocalStorage("theme", "light");

  return (
    <div>
      <div>Theme: {theme}</div>
      <button onClick={() => setItem("theme", theme === "light" ? "dark" : "light")}>
        Toggle
      </button>
      <button onClick={() => removeItem("theme")}>Reset</button>
    </div>
  );
}

When it updates

  • Same tab: setItem and removeItem dispatch an event that every useLocalStorage for that key listens to. Writing with localStorage.setItem directly does not notify the hook.
  • Other tabs: the browser's storage event updates the hook when another tab changes the key.
  • Server rendering: localStorage isn't available on the server, so the hook returns initialValue there and reads the stored value after mounting.

When the key is missing or removed, the hook returns initialValue.

Values are strings only. initialValue must be a string or null; anything else throws a TypeError. Use JSON.stringify / JSON.parse to store other data.

Parameters

Prop

Type

Return value

string | null: the stored value, or initialValue when the key is not set.

On this page