Today we will learn how to develop a Custom React-Js hook to determine whether the user has changed the browser tab or minimized the browser window. This hook will work for Chrome, Opera, Firefox, Edge, Safari etc…
Before we start we need to understand the concept of React-Js hook. React hooks provide super power to react library. A hook can be used to maintain the state of the application (useState()) or to execute some code when component mounts on the DOM, Updates on the DOM, Unmount from the DOM (useEffect()).
Here I used only two hooks, useState, and useEffect but this does not mean that React-Js power is limited. We can develop our own Hook.
I already posted an article about another hook to check if the user has a mobile device, Tablet or Desktop. And today we are here to develop another hook.
Let’s Start
Hook Development
- Create a file with the name useIsTabVisible.js and save this into your “src” directory.
- Now Copy and Paste the Code into your file.
import { useState, useEffect, useCallback } from 'react'
function useIsTabVisible() {
const [isVisible, setIsVisible] = useState(!document.hidden)
const handleVisibility = useCallback(() => {
setIsVisible(!document.hidden)
}, [])
useEffect(() => {
document.addEventListener('visibilitychange', handleVisibility)
return () => {
document.removeEventListener('visibilitychange', handleVisibility)
}
}, [handleVisibility])
return isVisible // returns boolean
}
export default useIsTabVisible
That’s it. Our hook is ready to use. Now we can use this hook in our project.
Hook Usage
Here is the code to use the hook in our react js component.
function MyComponent() {
const isVisible = isTabVisible()
return <>
{isVisible && <span>Status is Visible</span>}
</>
}
Hook Use Case
- You can use this hook to check if the user has changed the tab or lost focus from the browser tab.
- This type of hook can mainly be used on online exam portals where candidates are not allowed to change the browser tab.
- to detect how much time the user has lost focus from your page. Just send a request to the server and store the status data.
You must check out this article: How to check if the user has Mobile/Tablet/Desktop.
That’s all for today. I hope you have learned something interesting and useful. If you still have any doubt related to this hook/article please comment below. If you have any suggestions or ideas let us know in the comment section.
Thank You ❤️