Skip to content

Instantly share code, notes, and snippets.

@Wigny
Created October 13, 2025 13:01
Show Gist options
  • Select an option

  • Save Wigny/51e93f9bf7b88da196611a1a0fc443c6 to your computer and use it in GitHub Desktop.

Select an option

Save Wigny/51e93f9bf7b88da196611a1a0fc443c6 to your computer and use it in GitHub Desktop.
import { useSyncExternalStore, useMemo } from 'react';
export const useDocumentVisibility = (): boolean => {
const subscribe = useMemo(() => {
return (callback: () => void) => {
document.addEventListener('visibilitychange', callback);
return () => document.removeEventListener('visibilitychange', callback);
};
}, []);
const getSnapshot = useMemo(() => {
return () => document.visibilityState === 'visible';
}, []);
return useSyncExternalStore(subscribe, getSnapshot);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment