惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
I
InfoQ
Engineering at Meta
Engineering at Meta
Jina AI
Jina AI
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
Docker
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
博客园 - Franky
博客园 - 聂微东
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog RSS Feed
WordPress大学
WordPress大学
MyScale Blog
MyScale Blog
月光博客
月光博客
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Form drafts that survive a closed tab — and the 5 bugs ev...
Maaz Bin Tariq · 2026-06-23 · via DEV Community

Saving React form drafts to localStorage: five failure modes, three from one mistake

A user fills out a long form, the tab closes, and the work is gone. The fix looks like two useEffects. It isn't.

A naive "persist to localStorage" hook breaks in five distinct ways, and most of them never show up in the demo, the code review, or local testing. Three of the five aren't separate bugs at all — they're the same mistake showing up in three places.

The snippets below are distilled from use-form-draft, a small hook I wrote and put on npm. It's the worked example; the simplified versions here are easier to read than the production code, but they're the same ideas.

The five failure modes:

  1. The empty initial state overwrites a saved draft on first paint.
  2. React 18 StrictMode double-mounts and writes anyway.
  3. React Hook Form re-renders write to storage on every render.
  4. Accessing localStorage throws and takes the form down with it.
  5. A draft from an old schema corrupts the new form, or crash-loops it.

The first three share a single cause. The last two each need their own guard.

The naive version

useEffect(() => {
  localStorage.setItem(key, JSON.stringify(form));
}, [form]);

useEffect(() => {
  const saved = localStorage.getItem(key);
  if (saved) setForm(JSON.parse(saved));
}, []);

It looks right, and it works when you test it by hand. It breaks in the situations you don't hit locally.

Failure modes 1–3 share one cause

1. The empty state overwrites the draft on first paint. Effects run in the order they're declared, so the write effect goes first: it serializes the empty initial form straight over yesterday's saved draft. The restore effect runs immediately after and reads back the empty value that was just written. The draft is gone, and nothing brings it back.

2. StrictMode writes anyway. In development, React 18 StrictMode mounts, unmounts, and remounts to surface side-effect bugs. The usual patch for failure 1 (a mountedRef that skips the first run) fails here: the ref survives the remount and already reads true on the second mount. The guard lets the write through and clobbers the draft.

3. React Hook Form thrashes storage. form.watch() returns a new object reference on every render. A naive [values] dependency then fires a synchronous setItem on every keystroke and on every unrelated re-render up the tree. It works, but it writes far more than it should.

All three write because a render happened, not because the data changed. So compare the data. Keep the last thing you serialized, and write only when the new serialization differs:

// Seed with the initial serialized state, so the first run sees "no change"
// and writes nothing. This also covers StrictMode's double mount.
const lastWritten = useRef(JSON.stringify(state));

useEffect(() => {
  const json = JSON.stringify(state);
  if (json === lastWritten.current) return; // data didn't change → no write
  lastWritten.current = json;
  localStorage.setItem(key, json);
}, [state]);

That one comparison closes all three holes. The empty initial state matches the seed, so first paint writes nothing. StrictMode's second mount matches it too. And React Hook Form's fresh-but-identical object serializes to the same string, so none of those re-renders write. Only a real edit produces a different string.

Two caveats, since this leans on JSON.stringify as a content hash. It assumes the state is JSON-serializable with stable key order. For plain, string-keyed form objects that usually holds, though engines order integer-like keys numerically regardless of insertion, so avoid numeric field names. The bigger gap is values that don't round-trip: Map and Set both serialize to {}, undefined fields drop out, and NaN/Infinity become null. Any of those can make two different states hash the same and skip a write, so hash a normalized shape if your form holds them.

The full version in the package adds a debounce, strips excluded fields (passwords, card numbers) before hashing, and wraps the JSON.stringify itself, but the load-bearing idea is that one comparison.

Failure 4: accessing localStorage can throw

This one never reproduces on your machine, because your machine is fine.

Touching localStorage can throw, and not only when you write to it. A full quota or old Safari's private mode throws on the setItem. A sandboxed iframe, or a "block site data" policy, throws on the property access itself (window.localStorage) before any method runs, and typeof doesn't suppress that. (Modern Safari, Firefox, and Chrome private/incognito modes are fine: they give you a working, smaller-quota store and stopped throwing on normal writes years ago.)

Because all of this sits on the render path, an exception doesn't stay contained — it can take down the whole form the helper was meant to protect. So both the access and every method have to degrade to a quiet no-op:

function getStore(): Storage | null {
  try {
    return window.localStorage; // the access can throw, so guard it too
  } catch {
    return null;
  }
}

function safeSet(store: Storage | null, key: string, value: string) {
  if (!store) return;
  try {
    store.setItem(key, value);
  } catch {
    // quota full, disabled by policy, old Safari private mode.
    // a dropped draft is fine; crashing the form isn't.
  }
}

function safeRemove(store: Storage | null, key: string) {
  if (!store) return;
  try {
    store.removeItem(key);
  } catch {
    /* ignore */
  }
}

The same wrapping goes around getItem and JSON.stringify too (the latter throws on a BigInt or a circular reference). Persistence here is best-effort: a failed write just means there's no saved draft, which the user can live with. It never gets to throw into the form.

Failure 5: a stale draft corrupts the new schema

Forms change shape. You ship v2 where title goes from a string to { en, ar }, and a user still has a v1 draft in storage. You hydrate it, and last month's data pours into this month's inputs. Usually that just renders garbage — a blank field, a wrong value. Sometimes it throws, and if it throws unhandled, the broken draft stays in storage and crash-loops the form on every remount, so a refresh can't even rescue the user.

Two cheap guards handle it. Stamp a schema version on every draft and discard mismatches on read, and delete any draft whose hydrate throws.

type Draft<T> = { version: number; savedAt: string; state: T };

function read<T>(store: Storage | null, key: string, version: number): Draft<T> | null {
  if (!store) return null;
  try {
    const raw = store.getItem(key);
    if (!raw) return null;
    const draft = JSON.parse(raw) as Draft<T>;
    if (draft.version !== version) return null; // shape changed → discard
    return draft;
  } catch {
    return null; // corrupted JSON → discard
  }
}

// on mount:
const draft = read<FormShape>(store, key, SCHEMA_VERSION);
if (draft) {
  try {
    hydrate(draft.state);
  } catch {
    safeRemove(store, key); // one poisoned record can't break every visit
  }
}

Bump SCHEMA_VERSION on any incompatible change and old drafts get dropped on read instead of breaking the form. The same savedAt field also drives an expiry check and a "restored 3 minutes ago" label.

The tests are the proof

These are easy to fix once you know they exist. The catch is that all five are invisible until production, so they need tests that pin the behaviour rather than code that happens to work today. Each failure mode in the package is one named, runnable regression test: no write on the StrictMode double mount, no write on an identical-content re-render, a no-op when storage throws (including the property-access throw), a discarded draft on version mismatch, a deleted draft when hydrate throws. There's an SSR test too, for the server-render path.

When you might not need a library

If you only use React Hook Form and want no recovery UI, a smaller RHF-specific package will weigh less. If you want autosave to a server, this whole category is the wrong tool. And if your form state is plain and you just want the behaviour, the guard from the first section is most of the job — copy it.

But if you want the rest of it handled — the storage-throw guards, schema versioning, a debounce, a recovery banner, and adapters for React Hook Form, Formik, and TanStack Form — that's what use-form-draft packages. Either way, the test file is the fastest way to see each of these five bugs reproduced and fixed.