In today’s fast-paced digital world, optimizing user experience and resource management is crucial. One way to achieve this is by leveraging the Visibility API to detect whether your application is currently visible to the user. This can be particularly useful in scenarios where you want to conserve resources or enhance user engagement. In this post, we’ll explore how to create a custom React hook that utilizes the Visibility API to determine the visibility state of your application.
Creating the useDocVisible Hook
Let’s dive into the code and create a custom hook that detects the visibility state of your application.
import { useState, useEffect } from 'react'
export const useDocVisible = () => {
// Initialize state with the current visibility state
const [isVisible, setIsVisible] = useState(
typeof document !== 'undefined' && document.visibilityState === 'visible'
)
useEffect(() => {
// Define a handler to update the visibility state
const handleVisibilityChange = () => {
setIsVisible(document.visibilityState === 'visible')
}
// Add event listener for visibility change
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', handleVisibilityChange)
}
// Cleanup event listener on component unmount
return () => {
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
}
}, [])
return isVisible
}
How It Works
- State Initialization: We initialize the
isVisiblestate based on the current visibility state of the document. We ensure that this code only runs in the browser environment by checkingtypeof document !== 'undefined'. - Effect Hook: We use the
useEffecthook to set up an event listener for thevisibilitychangeevent. This event is triggered whenever the visibility state of the document changes. - Event Handler: The
handleVisibilityChangefunction updates theisVisiblestate based on the document’s visibility state. - Cleanup: We remove the event listener when the component unmounts to prevent memory leaks.
Use Cases
Here are some practical scenarios where this hook can be beneficial:
- Analytics: Track user engagement by sending data only when the user is away.
- Media Control: Pause or resume media playback based on visibility.
- Resource Management: Optimize server polling by stopping updates when the page is not visible.
Conclusion
By using the Visibility API, you can create a powerful custom hook that enhances your React application’s performance and user experience. Whether you’re managing media playback or optimizing server requests, this hook provides a simple yet effective solution.

Leave a Reply