Check if the Browser tab has Focus using React

avatar

Borislav Hadzhiev

Mon Apr 25 20221 min read

banner

Photo by Erik Mclean

Check if the Browser tab has Focus using React #

To check if the browser tab has focus using React:

  1. Add event listeners for the focus and blur events.
  2. If the focus event gets triggered, the tab has focus.
  3. If the blur event gets triggered, the tab has lost focus.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [tabHasFocus, setTabHasFocus] = useState(true); useEffect(() => { const handleFocus = () => { console.log('Tab has focus'); setTabHasFocus(true); }; const handleBlur = () => { console.log('Tab lost focus'); setTabHasFocus(false); }; window.addEventListener('focus', handleFocus); window.addEventListener('blur', handleBlur); return () => { window.removeEventListener('focus', handleFocus); window.removeEventListener('blur', handleBlur); }; }, []); return ( <div> {tabHasFocus ? ( <h2>Tab has focus ✅</h2> ) : ( <h2>Tab does not have focus ⛔️</h2> )} </div> ); }

check if tab has focus

We initialized a state variable that tracks whether the tab has focus or not.

We passed true to the useState hook to indicate that the tab is focused when the component mounts.

In our useEffect hook, we added event listeners for the focus and blur events. We added the events on the window object.

The focus event is triggered when the tab receives focus.

The blur event is triggered when the tab has lost focus.

We returned a function from our useEffect hook. The function is going be invoked when the component unmounts.

In our cleanup function, we use the removeEventListener method to remove the event listeners we previously registered.

This helps us avoid having memory leaks in our application.

Use the search field on my Home Page to filter through my more than 1,000 articles.