FrontendPro

60Implement useLocalStorage() with serialization and cross-tab updates

mediumAbout 35 minutesCodingreacthooksstorageevents

Problem

Implement useLocalStorage(key, initialValue, { serialize = JSON.stringify, deserialize = JSON.parse } = {}). It works like useState, but the value is stored in localStorage and stays in sync:

  • across tabs: when another tab changes the key, this component updates (the browser fires a storage event in other tabs);
  • across components in the same tab: two components using the same key show the same value (the storage event does not fire in the tab that made the change).

It returns [value, setValue, remove].

function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage("theme", "light");
  return <button onClick={() => setTheme((t) => (t === "light" ? "dark" : "light"))}>{theme}</button>;
}

Requirements

  • Read the stored value on the first render; fall back to initialValue when it is missing or cannot be parsed.
  • setValue accepts a value or an updater function, like useState, and writes the serialised value.
  • remove() deletes the key and resets to initialValue.
  • Never crash when storage is unavailable or full; keep the in-memory value working.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Write a read() helper: get the raw string, return initialValue when it is null, and wrap deserialize in try/catch so corrupt data (or a storage that throws, as in some private modes) also falls back to initialValue.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever