DAILY NEWS

Stay Ahead, Stay Informed – Every Day

Advertisement
React useDebounce Hook: Debounce State & Callbacks (2026)



You have a search box. The user types react hooks, and your component fires an API request on every single keystroke — eleven requests for one query, ten of them already stale by the time they resolve. The fix everyone reaches for is debouncing: wait until the typing stops, then fire once. The fix everyone gets wrong is writing that debounce by hand with setTimeout inside a component, where stale closures, missing cleanup, and re-render churn quietly break it.

useDebounce is the hook that gets it right. This post covers the two shapes you actually need — debouncing a value and debouncing a callback — when to use each, and how to cancel or flush pending calls. Everything here is the real @reactuses/core API, SSR-safe and typed.

Why Not Just Use setTimeout?

Debouncing itself is simple: delay a function until a quiet period has passed, restarting the timer on every new call. (If you want the full conceptual breakdown — and how it differs from throttling — see Debounce vs Throttle in React.) The hard part is doing it inside a React component. Here is the naive version, and it has three bugs:

function Search() {
const (query, setQuery) = useState(”);
const timer = useRefReturnTypetypeof setTimeout>>();

function handleChange(e: React.ChangeEventHTMLInputElement>) {
const value = e.target.value;
setQuery(value);
clearTimeout(timer.current);
timer.current = setTimeout(() => {
fetchResults(value); // 🐛 see below
}, 300);
}

return input value={query} onChange={handleChange} />;
}

Enter fullscreen mode

Exit fullscreen mode

It leaks on unmount. If the component unmounts while a timer is pending, the callback still fires 300 ms later — often setting state on a gone component, or hitting an API for a screen the user already left.

It captures stale values. The moment you debounce anything other than the raw event value — a second piece of state, a prop, a derived value — the closure freezes whatever those were when the timer was set, not when it fires.

It spreads. Every place that needs debouncing re-implements the useRef + clearTimeout dance, and each copy is a chance to forget the cleanup.

A hook fixes all three in one place. ReactUse ships two, built on the battle-tested lodash.debounce internally so the edge cases (leading edge, max wait, trailing edge) are already handled.

useDebounce — Debounce a Value

The most common case: you have a value that changes rapidly and you want a second, lagging copy of it that only updates after things settle. That second copy is what you feed into expensive work.

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

function Search() {
const (query, setQuery) = useState(”);
const debouncedQuery = useDebounce(query, 300);

useEffect(() => {
if (!debouncedQuery) return;
fetchResults(debouncedQuery);
}, (debouncedQuery));

return (
input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder=”Search…”
/>
);
}

Enter fullscreen mode

Exit fullscreen mode

The signature is useDebounce(value, wait?, options?) and it returns the debounced value, with the same type as the input:

const debounced = useDebounce(value, 300);

Enter fullscreen mode

Exit fullscreen mode

The input (query) updates on every keystroke, so the controlled stays perfectly responsive — that’s the value you bind to the DOM. The output (debouncedQuery) only catches up 300 ms after the user stops typing, so it’s the value you put in the effect’s dependency array. The API fires once per pause instead of once per keystroke, and your input never feels laggy because the thing you typed into was never the thing being debounced.

This pattern — fast value for the UI, debounced value for the side effect — is the whole point. Keep them as two separate variables and the rest falls into place.

useDebounceFn — Debounce a Callback

Debouncing a value is great when the thing you want to throttle is state. But sometimes you want to debounce an action that takes arguments — an autosave, an analytics event, a resize handler — without routing it through state first. That’s useDebounceFn:

import { useDebounceFn } from ‘@reactuses/core’;

function Editor({ docId }: { docId: string }) {
const { run } = useDebounceFn((content: string) => {
saveDraft(docId, content);
}, 1000);

return (
textarea onChange={(e) => run(e.target.value)} />
);
}

Enter fullscreen mode

Exit fullscreen mode

useDebounceFn(fn, wait?, options?) returns an object with three members:

const { run, cancel, flush } = useDebounceFn(fn, 1000);

Enter fullscreen mode

Exit fullscreen mode

run — the debounced function. Call it as often as you like; fn only actually executes after the calls stop for wait ms. It forwards every argument through, so run(content) calls fn(content).

cancel — drop any pending invocation. Nothing fires.

flush — fire the pending invocation right now, instead of waiting out the timer.

Crucially, run always calls the latest version of your fn. Internally the hook keeps your callback in a ref, so even though the debounced wrapper is created once, it never goes stale — the docId closure problem from the setTimeout version simply doesn’t exist here. And the hook cancels any pending call automatically on unmount, so bug #1 is gone too.

useDebounce is actually built on top of useDebounceFn — it debounces a setState call and hands you the resulting value. Same engine, two ergonomics.

cancel and flush in practice

The cancel/flush pair is what raw setTimeout makes painful and a hook makes trivial. Two real cases:

function CommentBox() {
const { run: autosave, cancel, flush } = useDebounceFn(
(text: string) => saveDraft(text),
2000,
);

return (

textarea onChange={(e) => autosave(e.target.value)} />
{/* User hit “Post” — persist immediately, don’t wait out the 2s */}
button onClick={() => flush()}>Postbutton>
{/* User hit “Discard” — throw away the pending autosave */}
button onClick={() => cancel()}>Discardbutton>
>
);
}

Enter fullscreen mode

Exit fullscreen mode

flush guarantees the in-flight draft is written before the post request goes out; cancel makes sure a discarded draft doesn’t get saved a beat later. Both are one call.

Value or Callback — Which One?

A quick decision rule:

Reach for useDebounce when you’re debouncing a piece of state that something else reads — a search term, a filter, a slider value feeding a chart. You want a lagging value.
Reach for useDebounceFn when you’re debouncing an action with arguments — autosave, logging, firing a network request directly. You want a lagging function, plus cancel/flush control.

If you find yourself creating a piece of state only to debounce it and then immediately fire an effect, useDebounceFn is usually the more direct tool.

Tuning: leading, trailing, and maxWait

The optional third argument is passed straight through to lodash.debounce, so you get its full options object:

useDebounce(value, 300, {
leading: false, // don’t fire on the very first call (default)
trailing: true, // fire after the pause (default)
maxWait: 1000, // …but never wait longer than 1s total
});

Enter fullscreen mode

Exit fullscreen mode

Two knobs worth knowing:

leading: true fires on the first call immediately, then debounces the rest. Good for “respond instantly, then settle” interactions — the first click of a button feels snappy while rapid repeats are absorbed.

maxWait caps the total delay. With a pure trailing debounce, a user who types continuously for ten seconds gets zero updates until they stop. maxWait: 1000 forces an update at least once a second even mid-burst — the difference between a search box that feels alive and one that feels frozen.

SSR Safety

Both hooks are safe to render on the server. They touch no window, document, or browser timer during render — the debounced work only ever runs inside effects, which React never executes on the server. Drop them into a Next.js, Remix, or Astro component and there’s no typeof window guard to write, no hydration warning to chase. (If SSR-safety is a running theme in your codebase, SSR-Safe React Hooks goes deeper.)

The Rate-Limiting Family

useDebounce has three close relatives in ReactUse; pick by what you’re limiting and which shape you need:

The throttle pair mirrors the debounce pair exactly — same (value/fn, wait, options) signature, same return shapes — but enforces a steady cadence instead of waiting for silence. Use throttle for things that should update during a continuous gesture (scroll position, drag coordinates, a live progress readout); use debounce for things that should update only after it ends (search, autosave, validation). The full mental model is in Debounce vs Throttle in React: When to Use Which.

Takeaways

A hand-rolled setTimeout debounce inside a component ships three bugs by default: it leaks on unmount, it captures stale closures, and it gets copy-pasted.

useDebounce(value, wait) gives you a lagging copy of a value — type into the fast one, run effects off the slow one. Perfect for search-as-you-type.

useDebounceFn(fn, wait) debounces an action and hands you { run, cancel, flush }. run always calls your latest callback (no stale closures) and auto-cancels on unmount.
Use flush to commit a pending call early (submit) and cancel to drop it (discard).
The third argument is lodash.debounce options — leading for instant-first-call, maxWait to cap the delay so long bursts still update.
Both are SSR-safe and sit alongside useThrottle/useThrottleFn for the fixed-rate case.

Grab them from @reactuses/core and delete your clearTimeout boilerplate.



Source link

DESIGN.md Anatomy: How Tokens and Prose Work Together



A DESIGN.md has two parts: YAML front matter with machine-readable design tokens, and a markdown body with human-readable rationale. Tokens give an agent exact values; prose gives it the rules. Pairing them is the format’s core insight.

The front matter: tokens

The front matter holds your colors, typography, spacing, rounded corners and components as typed values. It opens and closes with three dashes:


colors:
primary: “#1A1C1E”
surface: “#FFFFFF”
spacing:
sm: 8px
md: 16px

Enter fullscreen mode

Exit fullscreen mode

This gives the agent precise values to use directly.

The body: prose

Below the front matter is the rationale, in canonical sections:

## Overview
A calm, focused reading environment. The UI recedes so content leads.

## Colors
Warm neutrals carry the interface. The accent is reserved strictly
for interactive elements – never decorative.

Enter fullscreen mode

Exit fullscreen mode

Why pair them?

A hex value tells the agent what a color is. Only prose can tell it that this color is the sole interaction driver and must never be used decoratively.

# A tokens-only file: just data, no rules.
# A prose-only file: intent, but no precise values.
# DESIGN.md: both, so the agent applies the system correctly.

Enter fullscreen mode

Exit fullscreen mode

The canonical sections

Overview – the personality

Colors – roles and rules

Typography – the job of each style

Layout – grid and spacing

Elevation & Depth – how hierarchy is built

Do’s and Don’ts – hard guardrails

FAQ

Is the front matter required? In principle optional, but in practice it is the heart of the file.Can I use only prose? You can, but you lose precise values. The format is designed for both.

Bottom line

Tokens are the values; prose is the meaning. A DESIGN.md works because it carries both in one file the agent reads together.

Free starter: The format, a complete annotated example, and the core idea are on a free cheat sheet: DESIGN.md Quick-Start Cheat Sheet

Go deeper: The full guide covers the entire format — the token schema, the CLI in depth, accessibility, Tailwind and DTCG export, agent integration, and a complete walkthrough: DESIGN.md: The Complete Guide to Design Systems for AI Agents

Do you write rationale in your design docs, or just list the tokens? Curious how teams handle the ‘why’ in the comments.



Source link

Connection architectures for WordPress maintenance tools — mapping four products on a two-axis grid



While writing the comparison pages for ManageWP, MainWP, WP Umbrella, and InfiniteWP on our LP, I tried to line up the four products under a single “connection method” column — and got stuck. The same ManageWP gets called a “Hosted SaaS tool” in one source, a “Worker plugin tool” in another, and a “self-hosted” tool in yet another.

On closer look, these labels are mixing two distinct axes into one column. Once you separate them, the four products fit cleanly into a two-axis, six-cell grid. This post lays out that grid and walks through what each cell means for day-to-day operations.

Axis 1 — What gets installed on the client site

The first axis asks what the maintenance tool installs on the WordPress sites it manages. There are two answers.

A. Worker / Child plugin: Each managed site gets a dedicated plugin from the maintenance tool. ManageWP Worker, MainWP Child, WP Umbrella, InfiniteWP Client — the names differ, but they all play the same role: a “gateway plugin” that exposes a REST/HTTP endpoint the dashboard talks to.

B. Direct SSH + WP-CLI: Nothing gets installed on the site. The tool logs in via SSH and invokes WP-CLI directly on the server.

The difference shows up as how invasive the tool is on the client side. The plugin route carries the cost of “a vulnerability in the gateway plugin cascades to every managed site” and “you owe the client an explanation for the extra plugin.” The SSH route carries the constraint of “hosts that disallow SSH are out of reach” and “operators need basic SSH literacy.”

Axis 2 — Where the dashboard lives

The second axis asks where the dashboard itself runs. There are three answers.

① Hosted SaaS: The dashboard runs on infrastructure operated by the vendor. Site credentials live in their cloud — a trust model where the vendor holds your secrets.

② Self-hosted: You stand up your own WordPress site or server and install the dashboard there. The data stays in your control, but you also inherit the operational burden of maintaining that dashboard platform itself.

③ Desktop app: The dashboard runs on your local PC. Data stays local — no cloud component, no server to operate.

Axis 2 determines where the data lives and where the responsibility line is drawn. Who holds the credentials? Who is on the hook when something goes wrong? That cell choice shapes the risk structure your team takes on.

The two axes overlaid — a six-cell grid

Dashboard ↓ / Connection →
Worker / Child plugin
Direct SSH + WP-CLI

① Hosted SaaS
ManageWP, WP Umbrella
(industry gap)

② Self-hosted
MainWP, InfiniteWP
(industry gap)

③ Desktop app
(industry gap)
WP Maintenance Manager

The four major products cluster in the top two cells of the “plugin” column. The “SSH” column is almost entirely blank. Let’s walk through the three occupied cells first.

Cell 1 — Hosted SaaS × plugin (ManageWP, WP Umbrella)

The industry’s most classic configuration: browser access from anywhere, the vendor handles infrastructure updates and redundancy, and uptime monitoring fits naturally. WP Umbrella’s EU-based hosting, which leans on data-residency as a selling point, is a story this cell makes possible.

The trade-off is that client credentials get handed to a third-party cloud. A breach at the vendor cascades to every managed site, and your operations are tied to the vendor’s business continuity. Pricing tends to layer “per-site × add-on” charges on top of the monthly base.

Cell 2 — Self-hosted × plugin (MainWP, InfiniteWP)

For teams that don’t want credentials in a third-party cloud but still want the compatibility of plugin-based connections. Full data ownership and affinity with one-time-purchase and annual-license models are the upsides.

The trade-off is that the burden of maintaining the dashboard platform falls on you. MainWP requires you to keep updating and securing the very WordPress site that runs the dashboard; InfiniteWP’s panel server needs the same kind of care. A meta-recursion of “you maintain the tool that maintains your tools” is built into this cell. If the dashboard platform is compromised, the credentials for every connected site can leak from one place.

Cell 3 — Desktop × SSH (WP Maintenance Manager)

The dashboard runs as a desktop app on your PC, and the tool connects to sites directly over SSH. Three properties stand out: data lives only on the local PC, no infrastructure to operate, and nothing installed on client sites. The cascading-vulnerability risk of a gateway plugin structurally doesn’t exist.

The trade-off is that continuous uptime monitoring isn’t a natural fit — when the PC is asleep, the monitoring loop isn’t running. Hosts that disallow SSH also fall outside the supported set, so the hosting coverage is narrower than the other cells.

Why the three empty cells stay empty

The remaining cells have essentially no products. There are structural reasons.

Hosted SaaS × SSH struggles because handing SSH private keys to a cloud vendor is a trust model the market resists. Plugin-based connections keep credentials on the site side; storing and using SSH keys inside a third-party cloud raises the audit bar significantly.

Self-hosted × SSH is technically possible, but layers two costs at once: running your own dashboard platform and absorbing the SSH connectivity constraints. Teams that opt into self-hosting rarely want to give up plugin-route compatibility on top of that.

Desktop × plugin fights a fundamental mismatch: some gateway plugins assume continuous push communication to the dashboard, which doesn’t reconcile with a desktop app that only runs when the user’s PC is on.

Closing — how to choose a cell

Cell selection is a trade-off between acceptable costs and where the responsibility line sits. Three questions tend to do most of the work during evaluation.

Credentials in a third-party cloud, or kept locally? (Axis 2)

A maintenance plugin on every client site, or none? (Axis 1)

Operating an infrastructure tier yourself, or not? (Axis 2, only the self-hosted row adds this)

The industry has consolidated into “Hosted SaaS × plugin” and “Self-hosted × plugin” largely for historical reasons — SSH-route constraints (host coverage and the SSH knowledge requirement on operators) made industry-wide adoption hard. Choosing the SSH column structurally avoids the client-side invasiveness and gateway-plugin cascade risk that the plugin column carries.

There’s no single “correct” architecture. Operating style, client contracts, and data-handling requirements all shift the right cell. Carrying this six-cell map in your head makes it easier to ask the right comparison questions when picking a maintenance tool — and to see which trade-offs actually matter for your own operations.



Source link