Skip to content

Instantly share code, notes, and snippets.

@hmelenok
Created May 10, 2022 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmelenok/3c16c58cb3230838ff04a156d35cebb9 to your computer and use it in GitHub Desktop.
Save hmelenok/3c16c58cb3230838ff04a156d35cebb9 to your computer and use it in GitHub Desktop.
visibilitychange with react useSyncExternalStore
export function useVisibilityChange(serverFallback: boolean) {
const getServerSnapshot = () => serverFallback;
const [getSnapshot, subscribe] = useMemo(() => {
return [
() => document.visibilityState === 'visible',
(notify: () => void) => {
window.addEventListener('visibilitychange', notify);
return () => {
window.removeEventListener('visibilitychange', notify);
};
},
];
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment