useLocalStorage

Naseebullah Ahmadi  Senior Software Engineer, London

A `localStorage`-backed `useState` built on `useSyncExternalStore`: no hydration mismatch under SSR, live updates when another tab writes, and live updates when another hook on the same page writes.

3 min read
#frontend

localStorage is external mutable state that #react doesn't track, which is exactly what useSyncExternalStore is built for. Subscribe through it and you get the three things a hand-rolled useState + useEffect version usually drops: a server render that matches the client's first paint, updates when another tab writes, and updates when another instance of the hook on the same page writes.

@itsnas editor.tsx
codeeditor.tsx
'use client'
 
function Editor() {
  // @src/code/local-storage
  const [draft, setDraft] = useLocalStorage('editor:draft', '')
 
  return (
    <textarea
      value={draft}
      onChange={e => setDraft(e.target.value)}
      placeholder="Autosaved to this browser…"
    />
  )
}
main
Nas (@itsnas)