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

推荐订阅源

美团技术团队
W
WeLiveSecurity
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
F
Full Disclosure
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Register - Security
The Register - Security
G
Google Developers Blog
C
Check Point Blog
GbyAI
GbyAI
A
About on SuperTechFans
V
Vulnerabilities – Threatpost
T
The Blog of Author Tim Ferriss
T
Tor Project blog
AWS News Blog
AWS News Blog
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
MongoDB | Blog
MongoDB | Blog
Latest news
Latest news
aimingoo的专栏
aimingoo的专栏
U
Unit 42
Y
Y Combinator Blog
P
Privacy International News Feed
Cisco Talos Blog
Cisco Talos Blog
S
Securelist
S
Schneier on Security
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
C
Cisco Blogs
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
月光博客
月光博客
P
Privacy & Cybersecurity Law Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
罗磊的独立博客
Cloudbric
Cloudbric
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Security Blog
Microsoft Security 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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Form drafts that survive a closed tab — and the 5 bugs everyone ships first
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.