Last active
November 12, 2024 12:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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