@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:
setItemandremoveItemdispatch an event that everyuseLocalStoragefor that key listens to. Writing withlocalStorage.setItemdirectly does not notify the hook. - Other tabs: the browser's
storageevent updates the hook when another tab changes the key. - Server rendering:
localStorageisn't available on the server, so the hook returnsinitialValuethere 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.