Skip to content

Instantly share code, notes, and snippets.

@archangel-irk
Created August 12, 2019 06:08
Show Gist options
  • Save archangel-irk/0193267178b25b306d064986c134f444 to your computer and use it in GitHub Desktop.
Save archangel-irk/0193267178b25b306d064986c134f444 to your computer and use it in GitHub Desktop.
React Hook - Page Visibility API (tab document visible)
import { useEffect, useState } from 'react';
// Spec
// https://www.w3.org/TR/page-visibility-2/
// MDN
// https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
// https://developers.google.com/web/updates/2017/03/background_tabs
enum VisibilityState {
HIDDEN = 'hidden',
VISIBLE = 'visible',
}
const EVENT_NAME = 'visibilitychange';
export function isPageVisible(): boolean {
// Server-side rendering case
if (typeof document === 'undefined') return true;
return document.visibilityState === VisibilityState.VISIBLE;
}
function usePageVisibility(): boolean {
const [pageVisible, setPageVisible] = useState<boolean>(isPageVisible());
function handleVisibilityChange(event: Event): void {
setPageVisible(isPageVisible());
}
useEffect(function subscribeVisibilityChange(): () => void {
document.addEventListener(EVENT_NAME, handleVisibilityChange);
return function unsubscribeVisibilityChange(): void {
document.removeEventListener(EVENT_NAME, handleVisibilityChange);
};
}, []);
return pageVisible;
}
export { usePageVisibility };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment