Skip to content

Instantly share code, notes, and snippets.

@ibrennan
Last active February 20, 2024 21:23
Show Gist options
  • Save ibrennan/1681f013d14b69d0cef947f7b1ed9da0 to your computer and use it in GitHub Desktop.
Save ibrennan/1681f013d14b69d0cef947f7b1ed9da0 to your computer and use it in GitHub Desktop.
useVisibilityState - A simple React Hook for tracking document.visibilityState, useful for things like suspending API polling on inactive tabs
import { useState, useEffect, useCallback } from 'react';
export const useVisbilityState = () => {
const [visibilityState, setVisibilityState] = useState(null);
const handleVisbilityChange = useCallback(() => {
setVisibilityState(document.visibilityState);
}, [setVisibilityState]);
useEffect(() => {
document.addEventListener('visibilitychange', handleVisbilityChange);
return () =>
document.removeEventListener('visibilitychange', handleVisbilityChange);
}, [handleVisbilityChange]);
return visibilityState;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment