Desafío de Programación: Pregunta 16

Aprende a crear el hook useFocus en React con TypeScript para saber si el foco está dentro de un contenedor y sus descendientes mediante focusin y focusout

28 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Desafío de Programación: Pregunta 16. En este reto crearemos un hook useFocus que permite que un elemento padre detecte si el foco está dentro de alguno de sus descendientes y, en función de ello, realizar un render condicional.

Paso 1 crear la referencia y el estado. Usamos useRef para obtener el nodo y useState para mantener si hay foco o no. Ejemplo en TypeScript texto plano: const ref = useRef<T>(null); const [isFocused, setIsFocused] = useState(false)

Paso 2 en un useEffect obtener el nodo actual y si no existe devolver sin hacer nada. const node = ref.current if (!node) return

Paso 3 definir los manejadores de evento. Cuando el foco entra en el contenedor o en cualquiera de sus descendientes se marca isFocused en true. const handleFocusIn = () => setIsFocused(true)

Paso 4 cuando el foco sale del contenedor comprobamos event.relatedTarget para saber si el foco se trasladó fuera del contenedor y entonces ponemos isFocused en false. const handleFocusOut = (e: FocusEvent) => { if (node && !node.contains(e.relatedTarget as Node)) { setIsFocused(false) } }

Paso 5 añadir listeners al nodo para los eventos focusin y focusout y limpiar en el return del efecto. node.addEventListener("focusin", handleFocusIn) node.addEventListener("focusout", handleFocusOut) return () => { node.removeEventListener("focusin", handleFocusIn) node.removeEventListener("focusout", handleFocusOut) }

Código final de ejemplo en TypeScript mostrado como texto con entidades para los signos menor y mayor: import React, { useRef, useEffect, useState, Ref } from react export function useFocus<T extends HTMLElement>(): [Ref<T>, boolean] { const ref = useRef<T>(null); const [isFocused, setIsFocused] = useState(false); useEffect(() => { const node = ref.current if (!node) return const handleFocusIn = () => setIsFocused(true); const handleFocusOut = (e: FocusEvent) => { if (node && !node.contains(e.relatedTarget as Node)) { setIsFocused(false) } } node.addEventListener("focusin", handleFocusIn) node.addEventListener("focusout", handleFocusOut) return () => { node.removeEventListener("focusin", handleFocusIn) node.removeEventListener("focusout", handleFocusOut) } }, [ref.current]) return [ref, isFocused] }

Ejemplo de uso en un componente App texto plano: export function App() { const [ref, isFocused] = useFocus<HTMLDivElement>() return <div ref={ref}> <input placeholder=Primer Input /> <input placeholder=Segundo Input /> {isFocused && <p>focused</p>} </div> }

Consejos prácticos y buenas prácticas: usar focusin y focusout porque burbujean y permiten detectar cambios de foco dentro del contenedor sin tener que asignar listeners a cada descendiente. Asegurarse de limpiar los listeners para evitar fugas de memoria y declarar correctamente las dependencias del useEffect para que el listener se vuelva a registrar solo cuando cambie el nodo.

Sobre Q2BSTUDIO: Si buscas socios expertos en desarrollo de software a medida, aplicaciones a medida, inteligencia artificial o ciberseguridad, en Q2BSTUDIO ofrecemos soluciones integrales para empresas. Somos especialistas en software a medida y en la creación de aplicaciones adaptadas a procesos y necesidades específicas. También desarrollamos proyectos de inteligencia artificial para empresas y agentes IA y ofrecemos servicios de seguridad y pentesting para proteger tus activos digitales.

Puedes conocer nuestros servicios de desarrollo de aplicaciones y software a medida en desarrollo de aplicaciones y software multiplataforma y explorar nuestras soluciones de inteligencia artificial en IA para empresas y agentes IA. Además contamos con servicios cloud aws y azure, servicios inteligencia de negocio y soluciones con power bi para potenciar el reporting y la analítica.

Palabras clave relevantes para mejorar posicionamiento: 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. Si deseas que en Q2BSTUDIO adaptemos este hook a un proyecto real o lo integremos en una aplicación con integración en la nube o inteligencia de negocio, nuestro equipo puede ayudarte a implementarlo de forma robusta y segura.

Resumen final: el hook useFocus permite al componente padre saber si el foco está en cualquiera de sus descendientes usando una ref y listeners de focusin y focusout. Es una solución elegante para control de estado de foco en componentes complejos y puede integrarse fácilmente en proyectos de software a medida o en proyectos que usen inteligencia artificial y servicios cloud gestionados por Q2BSTUDIO.

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