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

推荐订阅源

WordPress大学
WordPress大学
Blog — PlanetScale
Blog — PlanetScale
S
Security @ Cisco Blogs
G
GRAHAM CLULEY
L
LINUX DO - 热门话题
AWS News Blog
AWS News Blog
P
Privacy International News Feed
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
腾讯CDC
美团技术团队
宝玉的分享
宝玉的分享
博客园 - 聂微东
小众软件
小众软件
T
Threat Research - Cisco Blogs
L
Lohrmann on Cybersecurity
雷峰网
雷峰网
T
Threatpost
The Hacker News
The Hacker News
P
Palo Alto Networks Blog
L
LangChain Blog
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
V
Vulnerabilities – Threatpost
NISL@THU
NISL@THU
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
T
Troy Hunt's Blog
F
Full Disclosure
博客园_首页
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
H
Heimdal Security Blog
Hacker News: Ask HN
Hacker News: Ask HN
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog
S
Security Affairs
量子位
Cloudbric
Cloudbric
H
Hacker News: Front Page
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LINUX DO - 最新话题
IT之家
IT之家
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Spread Privacy
Spread Privacy
Forbes - Security
Forbes - Security
Security Archives - TechRepublic
Security Archives - TechRepublic

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
React Form Handling: Debounced Validation, Auto-Save Drafts, and Controlled Inputs
reactuse.com · 2026-05-08 · via DEV Community

React Form Handling: Debounced Validation, Auto-Save Drafts, and Controlled Inputs

Forms are the most rewritten part of every React app. They look easy on day one — slap a <input>, wire onChange to useState, ship it. By month three, the same form has grown async username validation, an auto-saved draft, a custom date popover, and a controlled-or-uncontrolled toggle that has to play nicely with the design system. Each of those features pulls in its own ad-hoc state machine, its own effect cleanup, and its own pile of edge cases. The form file becomes the longest in the codebase, and nobody on the team wants to touch it.

This post walks through four primitives that every non-trivial form needs eventually: a debounced value to throttle async validation, a controlled-or-uncontrolled wrapper that lets a component accept either pattern, a localStorage-backed draft that survives refreshes, and a click-outside detector that closes popovers without leaking listeners. For each one we will build the manual version first so the trade-offs are visible, then swap it for a focused hook from ReactUse. At the end, we combine all four into a single account-settings form that validates as you type, auto-saves drafts, and handles a country-picker popover.

1. Debounced Async Validation

The Manual Way

The classic mistake in async validation is firing a request on every keystroke. The classic fix is setTimeout, and the classic bug is forgetting to clear the previous timer:

import { useEffect, useState } from "react";

function ManualUsernameField() {
  const [username, setUsername] = useState("");
  const [debounced, setDebounced] = useState("");
  const [status, setStatus] = useState<"idle" | "checking" | "ok" | "taken">("idle");

  useEffect(() => {
    const id = setTimeout(() => setDebounced(username), 400);
    return () => clearTimeout(id);
  }, [username]);

  useEffect(() => {
    if (!debounced) {
      setStatus("idle");
      return;
    }
    let cancelled = false;
    setStatus("checking");
    fetch(`/api/username?u=${encodeURIComponent(debounced)}`)
      .then((r) => r.json())
      .then((data) => {
        if (!cancelled) setStatus(data.available ? "ok" : "taken");
      });
    return () => {
      cancelled = true;
    };
  }, [debounced]);

  return (
    <label>
      Username
      <input value={username} onChange={(e) => setUsername(e.target.value)} />
      <span>{status}</span>
    </label>
  );
}

Enter fullscreen mode Exit fullscreen mode

There are two effects here doing two different jobs, and they have to stay in sync. The first one is a debouncer: turn rapid username changes into a single delayed debounced value. The second one is a request runner: when debounced changes, fire a request and ignore the result if a newer one comes back. Both effects need their own cleanup. If you forget the clearTimeout you double up requests; if you forget the cancelled flag you race and the older response can overwrite the newer one.

The real cost is not lines of code — it is that the debounce logic is welded to this particular field. Reuse it on the email field and you copy-paste the same five lines.

The ReactUse Way: useDebounce

useDebounce returns a value that lags behind its input by a fixed delay:

import { useEffect, useState } from "react";
import { useDebounce } from "@reactuses/core";

function UsernameField() {
  const [username, setUsername] = useState("");
  const debounced = useDebounce(username, 400);
  const [status, setStatus] = useState<"idle" | "checking" | "ok" | "taken">("idle");

  useEffect(() => {
    if (!debounced) {
      setStatus("idle");
      return;
    }
    let cancelled = false;
    setStatus("checking");
    fetch(`/api/username?u=${encodeURIComponent(debounced)}`)
      .then((r) => r.json())
      .then((data) => {
        if (!cancelled) setStatus(data.available ? "ok" : "taken");
      });
    return () => {
      cancelled = true;
    };
  }, [debounced]);

  return (
    <label>
      Username
      <input value={username} onChange={(e) => setUsername(e.target.value)} />
      <span>{status}</span>
    </label>
  );
}

Enter fullscreen mode Exit fullscreen mode

The first effect — the debouncing one — is gone. useDebounce owns the timer and its cleanup. What remains is the part that is genuinely about your form: when the debounced value changes, run a validation request and discard stale responses.

The hook also pairs naturally with the equivalent function-debouncer, useDebounceFn, when you want to debounce an event handler instead of a value — useful for "save on blur" and similar patterns where the trigger is a callback rather than a state change.

2. Controlled or Uncontrolled — Pick One, Support Both

The Manual Way

Library components have a recurring dilemma: should the consumer pass value and onChange, or should the component manage its own state with a defaultValue? The honest answer is "both, depending on who's calling." Most teams reinvent this pattern field by field:

function ManualToggle({
  value,
  defaultValue = false,
  onChange,
}: {
  value?: boolean;
  defaultValue?: boolean;
  onChange?: (next: boolean) => void;
}) {
  const isControlled = value !== undefined;
  const [internal, setInternal] = useState(defaultValue);
  const current = isControlled ? value : internal;

  const handleClick = () => {
    const next = !current;
    if (!isControlled) setInternal(next);
    onChange?.(next);
  };

  return (
    <button role="switch" aria-checked={current} onClick={handleClick}>
      {current ? "On" : "Off"}
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

The pattern is simple in isolation but a magnet for subtle bugs. What if the consumer flips between controlled and uncontrolled by passing undefined mid-render? What if they pass value but no onChange? React's own form inputs warn about both of these, but custom components rarely bother — and as your design system grows, the boilerplate is duplicated across every input, switch, slider, and date picker.

The ReactUse Way: useControlled

useControlled collapses the whole pattern into a single hook call:

import { useControlled } from "@reactuses/core";

function Toggle({
  value,
  defaultValue = false,
  onChange,
}: {
  value?: boolean;
  defaultValue?: boolean;
  onChange?: (next: boolean) => void;
}) {
  const [current, setCurrent] = useControlled({
    value,
    defaultValue,
    onChange,
  });

  return (
    <button
      role="switch"
      aria-checked={current}
      onClick={() => setCurrent(!current)}
    >
      {current ? "On" : "Off"}
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

The hook does three things you would otherwise write yourself:

  1. Decides controlled vs uncontrolled once, on the first render, and warns if the mode flips later — same diagnostic React's built-in inputs use.
  2. Returns a stable setter that internally branches on the mode: in uncontrolled mode it updates internal state; in controlled mode it just calls onChange and lets the parent re-render.
  3. Always reflects the latest source of truth. The first tuple element is value when controlled and the internal state when not, so consumers never see a mismatch.

You can drop this into any input-shaped component in your design system and stop thinking about the pattern.

3. Auto-Saving Form Drafts

The Manual Way

Long forms — onboarding flows, settings pages, content editors — should never lose a user's work to a refresh. The standard fix is to mirror the form state into localStorage, and the standard mistake is to do it on every keystroke:

function ManualDraftForm() {
  const [draft, setDraft] = useState(() => {
    if (typeof window === "undefined") return { title: "", body: "" };
    const raw = localStorage.getItem("post-draft");
    return raw ? JSON.parse(raw) : { title: "", body: "" };
  });

  useEffect(() => {
    localStorage.setItem("post-draft", JSON.stringify(draft));
  }, [draft]);

  return (
    <form>
      <input
        value={draft.title}
        onChange={(e) => setDraft((d) => ({ ...d, title: e.target.value }))}
      />
      <textarea
        value={draft.body}
        onChange={(e) => setDraft((d) => ({ ...d, body: e.target.value }))}
      />
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Three problems hide in those fifteen lines. First, the lazy initializer reads localStorage on every mount but does not re-read if another tab updated it — multi-tab editing breaks silently. Second, the JSON.parse will throw on corrupted data and crash the component on mount. Third, localStorage.setItem is synchronous and runs on every render, which on a fast-typing user can pin the main thread.

The SSR check at the top is the giveaway that this is a recipe other components in your codebase will copy and probably get wrong.

The ReactUse Way: useLocalStorage

useLocalStorage looks like useState and behaves like useState, but the value lives in storage:

import { useLocalStorage } from "@reactuses/core";

function DraftForm() {
  const [draft, setDraft] = useLocalStorage("post-draft", {
    title: "",
    body: "",
  });

  return (
    <form>
      <input
        value={draft.title}
        onChange={(e) => setDraft({ ...draft, title: e.target.value })}
      />
      <textarea
        value={draft.body}
        onChange={(e) => setDraft({ ...draft, body: e.target.value })}
      />
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

The hook handles the four things the manual version got wrong or skipped:

  1. SSR-safe initialization. On the server it returns the default; the stored value hydrates on the first client render without a mismatch.
  2. Cross-tab sync. Listens to storage events and updates state when another tab writes to the same key.
  3. JSON-safe. Catches parse errors and falls back to the default rather than crashing.
  4. Stable setter. The returned setter has a stable identity, so you can pass it to useEffect deps or memoized children without churn.

For really long forms you often want auto-save plus debounce. Combine with useDebounce from section 1 — debounce the form state, then write the debounced value to storage — and you get an editor that survives refreshes without thrashing the disk.

4. Closing Popovers with Click-Outside

The Manual Way

Country pickers, date pickers, autocomplete menus, and anything else that floats above the page have to close when the user clicks elsewhere. The textbook implementation listens on document:

function ManualPopover({ children }: { children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen((v) => !v)}>Toggle</button>
      {open && <div className="popover">{children}</div>}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

This works for the simple case and breaks the moment your popover renders into a portal. The ref.current.contains(...) check assumes the popover is a DOM descendant of the trigger, which it usually is not for a real design system — popovers escape overflow containers by mounting at the body root. You also have to decide between mousedown and click (the right answer is almost always mousedown, so the popover closes before a downstream click handler fires), and remember to skip the listener when closed to avoid wasting cycles on every page click.

The ReactUse Way: useClickOutside

useClickOutside accepts a ref (or list of refs) and a handler:

import { useRef, useState } from "react";
import { useClickOutside } from "@reactuses/core";

function Popover({ children }: { children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const triggerRef = useRef<HTMLDivElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);

  useClickOutside([triggerRef, popoverRef], () => setOpen(false));

  return (
    <>
      <div ref={triggerRef}>
        <button onClick={() => setOpen((v) => !v)}>Toggle</button>
      </div>
      {open && (
        <div ref={popoverRef} className="popover">
          {children}
        </div>
      )}
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

The list-of-refs form is what makes this work for portaled popovers: you mark both the trigger and the floating panel as "inside," and clicks anywhere else fire the handler. The hook also handles the mousedown choice for you, attaches the listener once at the document level (no per-component churn), and cleans up on unmount.

There is a closely related hook, useClickAway, with a slightly different API for cases where you only need a single target ref — pick whichever reads better in your component.

Putting It All Together: A Settings Form

Here is a complete account-settings form that uses all four hooks. The username validates as you type. The whole form auto-saves to localStorage. The notifications switch is a controlled-or-uncontrolled component. The country picker is a portal-friendly popover that closes on outside click.

import { useEffect, useRef, useState } from "react";
import {
  useDebounce,
  useControlled,
  useLocalStorage,
  useClickOutside,
} from "@reactuses/core";

interface Settings {
  username: string;
  country: string;
  notifications: boolean;
}

const COUNTRIES = ["United States", "Japan", "Germany", "Brazil", "India"];

function NotificationSwitch({
  value,
  defaultValue = true,
  onChange,
}: {
  value?: boolean;
  defaultValue?: boolean;
  onChange?: (next: boolean) => void;
}) {
  const [on, setOn] = useControlled({ value, defaultValue, onChange });
  return (
    <button
      type="button"
      role="switch"
      aria-checked={on}
      onClick={() => setOn(!on)}
      style={{
        width: 48,
        height: 24,
        borderRadius: 999,
        border: "none",
        background: on ? "#3b82f6" : "#cbd5e1",
        position: "relative",
        cursor: "pointer",
      }}
    >
      <span
        style={{
          position: "absolute",
          top: 2,
          left: on ? 26 : 2,
          width: 20,
          height: 20,
          borderRadius: "50%",
          background: "white",
          transition: "left 120ms ease",
        }}
      />
    </button>
  );
}

function CountryPicker({
  value,
  onChange,
}: {
  value: string;
  onChange: (next: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLUListElement>(null);

  useClickOutside([triggerRef, menuRef], () => setOpen(false));

  return (
    <div style={{ position: "relative", display: "inline-block" }}>
      <button
        ref={triggerRef}
        type="button"
        onClick={() => setOpen((v) => !v)}
        style={{
          padding: "6px 12px",
          borderRadius: 6,
          border: "1px solid #cbd5e1",
          background: "white",
          cursor: "pointer",
        }}
      >
        {value || "Select country"}</button>
      {open && (
        <ul
          ref={menuRef}
          style={{
            position: "absolute",
            top: "calc(100% + 4px)",
            left: 0,
            margin: 0,
            padding: 4,
            listStyle: "none",
            background: "white",
            border: "1px solid #cbd5e1",
            borderRadius: 8,
            boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
            minWidth: 180,
          }}
        >
          {COUNTRIES.map((c) => (
            <li
              key={c}
              onClick={() => {
                onChange(c);
                setOpen(false);
              }}
              style={{
                padding: "6px 10px",
                borderRadius: 4,
                cursor: "pointer",
                background: c === value ? "#eff6ff" : "transparent",
              }}
            >
              {c}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default function SettingsForm() {
  const [settings, setSettings] = useLocalStorage<Settings>("account-settings", {
    username: "",
    country: "",
    notifications: true,
  });

  const debouncedUsername = useDebounce(settings.username, 400);
  const [status, setStatus] = useState<"idle" | "checking" | "ok" | "taken">("idle");

  useEffect(() => {
    if (!debouncedUsername) {
      setStatus("idle");
      return;
    }
    let cancelled = false;
    setStatus("checking");
    fetch(`/api/username?u=${encodeURIComponent(debouncedUsername)}`)
      .then((r) => r.json())
      .then((data) => {
        if (!cancelled) setStatus(data.available ? "ok" : "taken");
      })
      .catch(() => {
        if (!cancelled) setStatus("idle");
      });
    return () => {
      cancelled = true;
    };
  }, [debouncedUsername]);

  return (
    <form
      style={{
        maxWidth: 480,
        display: "grid",
        gap: 16,
        fontFamily: "system-ui, sans-serif",
      }}
      onSubmit={(e) => e.preventDefault()}
    >
      <label style={{ display: "grid", gap: 4 }}>
        <span style={{ fontSize: 14, color: "#475569" }}>Username</span>
        <input
          value={settings.username}
          onChange={(e) =>
            setSettings({ ...settings, username: e.target.value })
          }
          style={{
            padding: "8px 10px",
            borderRadius: 6,
            border: "1px solid #cbd5e1",
          }}
        />
        <span style={{ fontSize: 12, color: "#64748b" }}>
          {status === "checking" && "Checking..."}
          {status === "ok" && "✓ Available"}
          {status === "taken" && "✗ Taken"}
        </span>
      </label>

      <label style={{ display: "grid", gap: 4 }}>
        <span style={{ fontSize: 14, color: "#475569" }}>Country</span>
        <CountryPicker
          value={settings.country}
          onChange={(country) => setSettings({ ...settings, country })}
        />
      </label>

      <label
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <span style={{ fontSize: 14, color: "#475569" }}>
          Email notifications
        </span>
        <NotificationSwitch
          value={settings.notifications}
          onChange={(notifications) =>
            setSettings({ ...settings, notifications })
          }
        />
      </label>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Four hooks, four responsibilities, zero overlap:

  • useDebounce turns rapid keystrokes into one delayed value, so async validation only fires after the user pauses
  • useControlled lets the switch component accept either a value prop or a defaultValue, without duplicating the branch logic
  • useLocalStorage persists the entire settings object across refreshes, with SSR-safe init and cross-tab sync
  • useClickOutside closes the country menu when the user clicks anywhere outside the trigger or the menu — including portaled rendering targets

The form file ends up roughly 200 lines of mostly markup. The fiddly browser plumbing — timer cleanup, SSR storage access, controlled-vs-uncontrolled detection, document-level listeners — lives inside library hooks that have already been tested across the patterns where teams usually get them wrong.

Installation

npm i @reactuses/core

Enter fullscreen mode Exit fullscreen mode

Related Hooks

  • useDebounce — Lag a value behind its input by a fixed delay
  • useDebounceFn — Debounce a callback rather than a value
  • useControlled — Build components that accept either controlled or uncontrolled props
  • useLocalStorageuseState that persists to localStorage with SSR safety and cross-tab sync
  • useSessionStorage — Same shape as useLocalStorage, scoped to the session
  • useClickOutside — Detect clicks outside one or more elements
  • useClickAway — Single-ref variant of click-outside detection
  • useToggle — Boolean state with an explicit toggle setter
  • usePrevious — Read the previous value of a piece of state, useful for change detection in forms

ReactUse provides 100+ hooks for React. Explore them all →