Function: useDocVisible()
useDocVisible(
options?):boolean
Defined in: use-doc-visible.ts:113
A custom React hook that tracks whether the browser document/tab is currently visible to the user.
This hook uses useSyncExternalStore to efficiently monitor the browser's visibility state,
providing optimal performance and preventing tearing in concurrent rendering scenarios.
It leverages the Page Visibility API to detect when users switch tabs, minimize the browser,
or return to the page.
The hook is particularly useful for optimizing application performance by pausing expensive operations when the user is not actively viewing the page, such as stopping API polling, pausing animations, or deferring computationally intensive tasks.
In server-side rendering environments, the hook safely defaults to true (visible state)
to prevent hydration issues and ensure consistent behavior across server and client.
The optional onChange callback provides a convenient way to respond to visibility changes
without needing additional useEffect hooks in the consuming component.
Parameters
options?
UseDocVisibleOptions
Optional configuration for the hook, including an onChange callback.
Returns
boolean
Returns true if the document is visible, false if it's hidden.
Examples
const isVisible = useDocVisible();
useEffect(() => {
if (isVisible) {
// Resume polling or animations
} else {
// Pause expensive operations
}
}, [isVisible]);
// With onChange callback
const isVisible = useDocVisible({
onChange: (visible) => {
console.log(`Tab is now ${visible ? 'visible' : 'hidden'}`);
}
});
// Pause video playback when tab is hidden
const videoRef = useRef<HTMLVideoElement>(null);
const isVisible = useDocVisible({
onChange: (visible) => {
if (videoRef.current) {
visible ? videoRef.current.play() : videoRef.current.pause();
}
}
});
For a live, editable example, see the useDocVisible docs page.