usePageVisibility
Is the tab visible?
Import
TypeScript
import { usePageVisibility } from '@/hooks';API
Signature
usePageVisibility(default?) → boolean
When to use
Use usePageVisibility instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Returns defaults on the server; hydrates on the client.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · usePageVisibilityEditor
function PauseVideo({ video }: { video: HTMLVideoElement | null }) { const visible = usePageVisibility(); if (video) visible ? void video.play() : video.pause(); return null; }
Preview
Implementation source
Full library source for usePageVisibility — copy into your project when you are not installing a package yet.
hooks/browser/usePageVisibility.ts
import { useCallback, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useDocumentEvent } from '../events/useDocumentEvent';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
/** `true` when the page is visible. SSR-safe. */
export function usePageVisibility(defaultVisible = true): boolean {
const [visible, setVisible] = useState(() =>
isBrowser() ? document.visibilityState === 'visible' : defaultVisible,
);
const update = useCallback(() => {
if (isBrowser()) {
setVisible(document.visibilityState === 'visible');
}
}, []);
useIsomorphicLayoutEffect(() => {
update();
}, [update]);
useDocumentEvent('visibilitychange', update);
return visible;
}
Copy-paste example
usePageVisibility.example.tsx
'use client';
import { usePageVisibility } from '@/hooks';
export function PauseVideo({ video }: { video: HTMLVideoElement | null }) {
const visible = usePageVisibility();
if (video) visible ? void video.play() : video.pause();
return null;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
- Source of truth: open
hooks/browser/usePageVisibility.tsfor implementation details