Errores comunes de cierres desactualizados en React

Guía práctica para evitar clausuras desactualizadas en React: actualizaciones funcionales, dependencias en hooks, refs y patrones para timers, async y listeners con ejemplos.

20 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En React los llamados errores por cierre desactualizado o stale closure ocurren cuando una función guarda en su clausura valores viejos de estado o props y sigue usándolos aunque hayan cambiado. A continuación explico los casos más comunes y cómo resolverlos con ejemplos pequeños y aplicables.

1) setInterval usando un valor antiguo de estado

Problema: un callback de setInterval captura el valor de count de la primera renderización y nunca ve las actualizaciones posteriores. Ejemplo problemático: function BadCounter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => { setCount(count + 1) }, 1000) return () => clearInterval(id) }, []) } Explicación: la dependencia vacía hace que el callback use siempre el count inicial.

Solución recomendada: usar la actualización funcional para leer siempre el último estado sin depender de deps. Ejemplo: useEffect(() => { const id = setInterval(() => { setCount(c => c + 1) }, 1000) return () => clearInterval(id) }, []) Alternativa: incluir count en deps y recrear el intervalo cuando cambie, aunque es menos eficiente.

2) función async que lee una prop o estado viejo

Problema: una búsqueda asíncrona usa el valor antiguo de searchTerm que quedó en la clausura. Ejemplo problemático: function BadSearch({ searchTerm }) { const [results, setResults] = useState([]) useEffect(() => { async function run() { const res = await fetch('/api?q=' + encodeURIComponent(searchTerm)) const data = await res.json() setResults(data) } run() }, []) } Solución: poner la variable en el array de dependencias y manejar carreras con una bandera de cancelado. Ejemplo: useEffect(() => { let cancelled = false ; (async () => { const res = await fetch('/api?q=' + encodeURIComponent(searchTerm)) const data = await res.json() if (! cancelled) setResults(data) })() return () => { cancelled = true } }, [searchTerm])

3) listeners de eventos que mantienen estado viejo

Problema: un listener global agregado una sola vez lee valores antiguos desde su clausura. Ejemplo problemático: useEffect(() => { function onKey(e) { if (e.key === 'ArrowUp') setValue(value + 1) } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, []) Soluciones: A) usar actualizador funcional dentro del handler para evitar deps: function onKey(e) { if (e.key === 'ArrowUp') setValue(v => v + 1) } B) patrón ref: mantener el último valor en un ref y leer ref.current desde un handler estable adjuntado una sola vez.

4) handlers throttled o debounced con clausuras antiguas

Problema: funciones throttle o debounce creadas una vez capturan estado viejo si leen directamente variables externas. Soluciones: evitar leer estado dentro del handler y derivar todo de los argumentos del evento, o mantener el valor actual en un ref que se actualiza en un efecto y leer ref.current dentro de la función throttled.

Checklist rápido para evitar stale closures

• Usar actualizaciones funcionales setState(prev => compute(prev)) cuando sea posible. • Poner en el array de dependencias cualquier variable externa que uses dentro de un hook. • Si necesitas una referencia estable, guarda el valor actual en un ref y lee ref.current desde callbacks estables. • Recrear timers y listeners cuando sus dependencias cambien y siempre limpiar en el return del efecto. • Para throttles o debounces, prefiere derivar datos del evento o leer desde un ref.

En Q2BSTUDIO ayudamos a equipos a evitar este tipo de errores y a construir aplicaciones robustas y escalables. Somos una empresa de desarrollo de software a medida y aplicaciones a medida, especialistas en inteligencia artificial, ciberseguridad y servicios cloud. Si buscas desarrollar una solución personalizada consulta nuestros servicios de desarrollo en software a medida y aplicaciones a medida y si tu foco es IA descubre nuestras propuestas en inteligencia artificial para empresas. Integramos agentes IA, soluciones de power bi y servicios inteligencia de negocio, además de ofrecer ciberseguridad, pentesting y servicios cloud aws y azure para cubrir todo el ciclo de vida de tus proyectos.

Si necesitas auditoría de código, automatización de procesos o formación para tu equipo sobre buenas prácticas en hooks y gestión de estado, en Q2BSTUDIO podemos ayudarte a reducir bugs por cierres desactualizados y mejorar la calidad del software. Palabras clave relevantes: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat