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

推荐订阅源

Recorded Future
Recorded Future
爱范儿
爱范儿
Y
Y Combinator Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
腾讯CDC
罗磊的独立博客
阮一峰的网络日志
阮一峰的网络日志
Know Your Adversary
Know Your Adversary
P
Proofpoint News Feed
T
Tailwind CSS Blog
Attack and Defense Labs
Attack and Defense Labs
G
GRAHAM CLULEY
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
T
The Blog of Author Tim Ferriss
T
The Exploit Database - CXSecurity.com
博客园 - 叶小钗
Latest news
Latest news
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The Hacker News
The Hacker News
量子位
S
Security @ Cisco Blogs
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
美团技术团队
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
IT之家
IT之家
U
Unit 42
Project Zero
Project Zero
B
Blog
博客园 - 【当耐特】
D
DataBreaches.Net
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
F
Full Disclosure
Vercel News
Vercel News
NISL@THU
NISL@THU
AWS News Blog
AWS News Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
T
Threatpost
Martin Fowler
Martin Fowler
Engineering at Meta
Engineering at Meta
T
Tor Project blog
M
MIT News - Artificial intelligence
V
V2EX

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
Timers in React Without setTimeout: useTimeout, useInterval, useCountDown, and useRafFn
reactuse.com · 2026-05-18 · via DEV Community

Timers in React Without setTimeout: useTimeout, useInterval, useCountDown, and useRafFn

Timers are one of those things every React developer writes by hand the first ten times and gets wrong on at least six of them. The pattern looks simple: call setTimeout in a useEffect, return a cleanup function, ship it. Then a code review finds the stale closure. Then a bug ticket arrives because the delay is being read from props at mount instead of from the current render. Then someone notices the interval keeps running after the component unmounts on a slow page. Then you discover that setInterval drifts a little every cycle and your countdown is off by 800ms after a minute. Then your performance audit flags the animation loop that nobody remembered to pause when the tab was hidden.

None of these bugs are interesting. They are all the same kind of bug: the timer logic is fine, the React integration is what breaks. ReactUse ships six small hooks that handle this integration once and let you write the timer logic by itself: useTimeout, useTimeoutFn, useInterval, useCountDown, useRafFn, and useRafState.

This post walks each one — what the underlying primitive is, what the manual version looks like in React, what bug the hook hides, and where it actually belongs in your code. By the end you should know which timer hook to reach for and why.

The Problem in One Snippet

Before any hooks, here is what almost every React codebase does at least once:

function Toast({ message, durationMs }: { message: string; durationMs: number }) {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const id = setTimeout(() => setVisible(false), durationMs);
    return () => clearTimeout(id);
  }, [durationMs]);

  return visible ? <div className="toast">{message}</div> : null;
}

Enter fullscreen mode Exit fullscreen mode

That is correct, mostly. The bug is what is missing:

  1. The dependency array re-runs the effect every time durationMs changes — so a parent updating the prop mid-flight restarts the timer from zero instead of letting it finish.
  2. There is no way to cancel the timer from outside (e.g., a "dismiss" button) without lifting the visible state up.
  3. There is no way to read whether the timer is still pending — useful for tests, for analytics, for showing a "fading in 2s..." label.
  4. The cleanup runs on unmount, which is good, but it also runs on every re-render that touches durationMs, which is usually not what you want.

You can fix all four with useRef plumbing, but it is the kind of plumbing nobody enjoys writing twice. That is exactly what useTimeoutFn exists for.

1. useTimeoutFn — The Correct setTimeout

useTimeoutFn(callback, interval, options?) schedules callback after interval ms and returns [isPending, cancel, restart]. Three concrete things it does that the naive version does not:

  • The latest callback is always called — no stale closures even if you do not list the callback in deps.
  • cancel() lets a parent or sibling component stop the timer without unmounting.
  • restart() lets you reset the clock without changing keys or remounting.

Rewriting Toast:

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

function Toast({ message, durationMs, onClose }: {
  message: string;
  durationMs: number;
  onClose: () => void;
}) {
  const [isPending, cancel, restart] = useTimeoutFn(onClose, durationMs);

  return (
    <div className="toast" onMouseEnter={cancel} onMouseLeave={() => restart()}>
      {message}
      {isPending && <span className="fade-bar" />}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Notice what disappeared: no useEffect, no setTimeout, no clearTimeout, no useRef, no useCallback. The hover behavior — pause the auto-dismiss while the user is reading the toast — is a one-liner. The isPending flag drives the fade bar without any extra state.

The immediate option (default true) controls whether the timer starts on mount. Set it to false for "fire on demand":

const [, , scheduleSave] = useTimeoutFn(saveDraft, 2000, { immediate: false });

return <textarea onChange={(e) => { setText(e.target.value); scheduleSave(); }} />;

Enter fullscreen mode Exit fullscreen mode

Every keystroke pushes the save 2 seconds into the future. This is one way to build a "save 2 seconds after the user stops typing" debounce, though useDebounceFn is usually the cleaner choice for that specific pattern.

2. useTimeout — When You Just Want a Re-Render After N Milliseconds

useTimeout(ms, options?) is the same thing as useTimeoutFn but the callback is the component's own re-render. Useful when you want a piece of UI to "appear after a delay" without storing a boolean.

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

function DelayedSpinner({ delayMs = 250 }: { delayMs?: number }) {
  const [isPending] = useTimeout(delayMs);
  return isPending ? null : <Spinner />;
}

Enter fullscreen mode Exit fullscreen mode

The use case is "don't show a spinner for sub-250ms loads." If the parent finishes loading in 100ms, the spinner is never seen — no flash. If it takes longer, the spinner appears. No state, no effect, no boolean.

Same return shape as useTimeoutFn, so cancel and restart are there if you need to interrupt the re-render. In practice the read pattern dominates.

3. useInterval — The setInterval That Actually Pauses

useInterval(callback, delay, options?) runs callback every delay ms. The return value is { isActive, pause, resume }, not a tuple — useInterval is built around the pause/resume idea because that is the operation everyone needs and nobody implements correctly with raw setInterval.

The most common bug with setInterval in React is not the cleanup — modern linters catch that — it is passing null to stop the timer. With useInterval, that pattern just works:

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

function Polling({ active, onTick }: { active: boolean; onTick: () => void }) {
  useInterval(onTick, active ? 5000 : null);
  return null;
}

Enter fullscreen mode Exit fullscreen mode

When active flips to false, the delay becomes null and the interval clears. When it flips back, the interval restarts at the new delay. No useEffect, no ref dance, no "did I clean up on the right value of active" worry.

If you prefer explicit pause/resume from outside the hook (for example, pausing polling while the user is offline), use the controls: true option and take the controls:

const { isActive, pause, resume } = useInterval(refresh, 5000, {
  controls: true,
  immediate: true,
});

useEffect(() => {
  const onVisibilityChange = () =>
    document.hidden ? pause() : resume();
  document.addEventListener("visibilitychange", onVisibilityChange);
  return () => document.removeEventListener("visibilitychange", onVisibilityChange);
}, [pause, resume]);

Enter fullscreen mode Exit fullscreen mode

That snippet alone fixes a class of bugs that ships to production all the time: polling that continues at full rate while the user is on another tab, burning battery and rate-limited quota.

Why Not setInterval + Drift Correction?

setInterval does not guarantee an exact delay between calls — the browser may delay or batch callbacks when the page is throttled (background tab, low battery, Chrome's "intensive throttling"). For a polling loop this is fine. For a clock display it is visibly wrong: after 60 ticks of "every 1000ms" the displayed time can be a second or two behind the actual wall clock.

For clocks specifically, do not use useInterval to drive the display value. Use useInterval to schedule re-renders and read Date.now() inside the render:

function Clock() {
  const [, force] = useState(0);
  useInterval(() => force((n) => n + 1), 1000);
  return <span>{new Date().toLocaleTimeString()}</span>;
}

Enter fullscreen mode Exit fullscreen mode

The interval is allowed to drift; the displayed time is read fresh on every render. Drift becomes a re-render scheduling concern, not a correctness concern.

4. useCountDown — Hours, Minutes, Seconds Without the Date Math

Countdowns are intervals with extra responsibility: track remaining time, format it for display, fire a callback when it hits zero, and stop the timer afterwards. The component-level version of this looks like 30 lines of code that everybody has written at least once.

useCountDown(time, format?, callback?) returns a [hours, minutes, seconds] tuple of strings (zero-padded) and handles all of the above:

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

function OtpResend({ onExpire }: { onExpire: () => void }) {
  const [h, m, s] = useCountDown(60, undefined, onExpire);
  const expired = h === "00" && m === "00" && s === "00";

  return expired
    ? <button onClick={() => /* request again */ undefined}>Resend code</button>
    : <span>Resend in {m}:{s}</span>;
}

Enter fullscreen mode Exit fullscreen mode

The hook owns the interval, the remaining-time state, and the callback dispatch. The component owns the rendering decision. If you want a different format (for example, Xm Ys or a raw seconds count), pass a format function that takes the remaining-seconds number and returns three strings — the hook calls it on every tick and returns whatever you give it.

useCountDown clamps to ["00", "00", "00"] once time runs out, and refuses to overflow past 99 hours, so you do not have to defend the view layer against silly inputs.

5. useRafFn — When You Need 60fps, Not "About Once Per Second"

setInterval(fn, 16) is the wrong way to run something on every frame. The browser already has a primitive for "do this once per frame, synchronized to the display refresh, and skip it if the tab is hidden" — requestAnimationFrame. useRafFn(callback, initiallyActive?) is the React wrapper around it.

The callback receives the current high-resolution timestamp (the same value requestAnimationFrame passes to its callback), and the hook returns [stop, start, isActive].

A canvas particle simulation, a smooth scroll position read, a CSS-variable-driven animation — anything that needs to update every frame should use useRafFn:

import { useRafFn } from "@reactuses/core";
import { useRef } from "react";

function FollowCursor() {
  const ref = useRef<HTMLDivElement>(null);
  const target = useRef({ x: 0, y: 0 });
  const current = useRef({ x: 0, y: 0 });

  useEffect(() => {
    const onMove = (e: MouseEvent) => { target.current = { x: e.clientX, y: e.clientY }; };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  useRafFn(() => {
    // Spring-ish lerp toward the target each frame
    current.current.x += (target.current.x - current.current.x) * 0.15;
    current.current.y += (target.current.y - current.current.y) * 0.15;
    if (ref.current) {
      ref.current.style.transform = `translate3d(${current.current.x}px, ${current.current.y}px, 0)`;
    }
  });

  return <div ref={ref} className="follower" />;
}

Enter fullscreen mode Exit fullscreen mode

Two things to notice. First, the animation does not call setState. Pushing to ref.current.style keeps the work outside React's render cycle, which is the only way to get a real 60fps on a non-trivial page. Second, when the tab is hidden the browser stops firing requestAnimationFrame automatically — no useInterval-style throttling cliff, no manual pause logic needed for the common case.

If you do want manual control (for example, only animate while a panel is open), pass false as the second argument and call start()/stop() from your effect.

6. useRafState — Batched State Updates for Animations You Actually Re-render

useRafFn is great when you can mutate DOM directly. Sometimes you cannot — you have to push the new value into React state because it drives a JSX subtree. The naive version of this is:

const [pos, setPos] = useState({ x: 0, y: 0 });
// ... 60 setPos calls per second when the cursor moves

Enter fullscreen mode Exit fullscreen mode

That works, but every setPos triggers a render. If the cursor fires mousemove faster than 60Hz (some browsers do), you get more renders than frames. useRafState solves this by batching state updates to requestAnimationFrame — at most one render per frame, even if setState is called many times in between.

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

function CursorBadge() {
  const [pos, setPos] = useRafState({ x: 0, y: 0 });

  useEventListener("mousemove", (e) => {
    setPos({ x: e.clientX, y: e.clientY });
  });

  return <div style={{ left: pos.x, top: pos.y }} className="badge" />;
}

Enter fullscreen mode Exit fullscreen mode

The component re-renders at most 60 times per second regardless of how many mousemove events fire. It is a one-line drop-in replacement for useState whenever the source of updates is a high-frequency browser event (mouse, scroll, resize) and the target is JSX.

Pair this with useEventListener for the event side; pair with useRafFn instead when the target is a DOM mutation.

When to Use Which

The decision is not about preference — each hook fits a specific shape of problem:

You need to... Reach for
Run a callback once after N ms useTimeoutFn
Force a re-render once after N ms useTimeout
Run a callback every N ms with pause/resume useInterval
Display hh:mm:ss remaining useCountDown
Do work every frame, no React state useRafFn
Update React state on every frame at most useRafState
Wait until the user stops typing useDebounceFn
Cap callback rate to once per N ms useThrottleFn

The last two — useDebounceFn and useThrottleFn — are not strictly timer hooks, but they live in the same family. The short version is "stop a high-frequency event from firing too often" rather than "schedule work in the future."

Three Mistakes the Hooks Quietly Prevent

A few subtle bugs the hooks above make impossible.

Mistake 1: The setTimeout in useState Initializer

const [id] = useState(() => setTimeout(callback, 1000)); // wrong

Enter fullscreen mode Exit fullscreen mode

This schedules a timer that survives across React's intentional double-invocation in Strict Mode, and there is no cleanup. The "fix" with effects and refs is several lines. useTimeoutFn(callback, 1000) is one line and double-invocation safe by construction.

Mistake 2: Reading State Inside an Interval Callback

const [count, setCount] = useState(0);
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []); // captures count=0 forever — count goes 0, 1, 1, 1, 1...

Enter fullscreen mode Exit fullscreen mode

This is the most-Googled React timer bug. The fix in plain React is either the functional updater (setCount((c) => c + 1)) or a ref. The fix with useInterval is "it already works" — the hook routes the latest callback through a ref internally.

Mistake 3: Animating React State at 60fps

const [x, setX] = useState(0);
useEffect(() => {
  const tick = () => { setX((v) => v + 1); requestAnimationFrame(tick); };
  requestAnimationFrame(tick);
}, []);

Enter fullscreen mode Exit fullscreen mode

This works for one component. With ten on screen, React's render queue starts dropping frames because each setState triggers a full reconciliation. useRafFn lets you mutate DOM directly without going through React; useRafState caps re-renders to one per frame when DOM mutation is not an option. Either is correct; the loop above is correct only by accident.

Putting It Together: A "Tab Idle Refresher"

A small, realistic component to close on — a data card that polls every 30 seconds while the tab is visible and the user is active, and shows a countdown to the next refresh:

import { useInterval, useCountDown } from "@reactuses/core";
import { useState, useCallback } from "react";

function LiveStat({ fetchValue }: { fetchValue: () => Promise<number> }) {
  const [value, setValue] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [, m, s] = useCountDown(30);

  const refresh = useCallback(async () => {
    try {
      setValue(await fetchValue());
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Unknown error");
    }
  }, [fetchValue]);

  useInterval(refresh, 30_000, { immediate: true });

  return (
    <div className="card">
      <div className="value">{value ?? ""}</div>
      <div className="footer">
        {error ? `Error: ${error}` : `Next refresh in ${m}:${s}`}
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

useInterval owns the polling cadence. useCountDown owns the visual ticker. Neither is told about the other; both happen to land on the same number because they are seeded with the same constant. Two hooks, no useEffect, no setTimeout, no useRef.

Try Them Out

Every hook in this post has a runnable demo on its docs page. The fastest way to absorb the API surface is to read the demo, change one prop, and see what breaks:

Install with npm install @reactuses/core (or pnpm add @reactuses/core) and import directly. No provider, no setup, no peer dependencies beyond React 16.8+. The full hook list and source for everything we discussed is at reactuse.com.

Stop writing setTimeout in useEffect. The right hook for the job exists, and it is shorter.