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

推荐订阅源

The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
博客园 - Franky
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
WordPress大学
WordPress大学
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
MyScale Blog
MyScale Blog
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
博客园 - 【当耐特】
P
Proofpoint News Feed
D
DataBreaches.Net

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
Escaping the Trap: Fixing Stale Closures in React Hooks ⚡
Prajapati Paresh · 2026-06-16 · via DEV Community
Cover image for Escaping the Trap: Fixing Stale Closures in React Hooks ⚡

Prajapati Paresh

The Silent Interval Bug

When building dynamic dashboards at Smart Tech Devs, you frequently need to implement background timers. Whether it's an auto-save mechanism, a session timeout countdown, or a polling engine, developers reach for setInterval inside a React useEffect hook.

This is where the most notorious architectural trap in React occurs: the Stale Closure. You set an interval to auto-save a document every 5 seconds, but when the interval fires, it saves an empty document, even though the user has been typing paragraphs of text! The interval is silently trapped in the past, executing logic on an outdated snapshot of the React state.

Understanding the Trap

When useEffect runs on the initial render, it "captures" the variables in its scope. If you don't add the documentText state to the dependency array, the setInterval callback will forever reference the text exactly as it was on the first render (empty). If you do add it to the dependency array, React will destroy and recreate the interval on every single keystroke, causing severe performance issues and erratic timing bugs.

The Solution: The Mutable Ref Pattern

To solve this, we must decouple the *execution* of the timer from the *data* it needs to access. We achieve this using React's useRef hook to maintain a mutable, constantly updated reference to the latest state, without triggering re-renders or resetting the interval.


// components/dashboard/AutoSaveEditor.tsx
"use client";

import React, { useState, useEffect, useRef } from 'react';

export default function AutoSaveEditor() {
    const [text, setText] = useState('');
    
    // 1. Establish a mutable ref to hold the latest state
    const latestTextRef = useRef(text);

    // 2. Keep the ref perfectly synchronized with the React state
    useEffect(() => {
        latestTextRef.current = text;
    }, [text]);

    useEffect(() => {
        // 3. Initialize the interval EXACTLY ONCE (empty dependency array)
        const timer = setInterval(() => {
            // 4. Access the mutable ref inside the callback! 
            // It will always point to the fresh, current data, bypassing the stale closure.
            const currentData = latestTextRef.current;
            
            console.log("Auto-saving securely to database:", currentData);
            // executeApiSave(currentData);
            
        }, 5000);

        return () => clearInterval(timer);
    }, []); // Empty array ensures the timer is never erratically destroyed

    return (
        <div className="p-6 bg-white border shadow-sm rounded-xl">
            <h3 className="font-bold text-gray-800 mb-2">Enterprise Notes</h3>
            <p className="text-xs text-green-600 mb-4">Saving automatically every 5 seconds...</p>
            
            <textarea 
                value={text}
                onChange={(e) => setText(e.target.value)}
                className="w-full h-48 p-3 border rounded focus:ring-2 ring-purple-500"
                placeholder="Start typing..."
            />
        </div>
    );
}

The Engineering ROI

Stale closures are the leading cause of silent data loss and erratic UI behavior in React applications. By mastering the useLatest reference pattern, you guarantee that asynchronous background tasks (like timers, socket listeners, and heavy throttlers) always execute against accurate data without crippling your component's rendering performance.