Last active
May 7, 2021 16:29
-
-
Save jyoo/3ede2aae60490354a91aab60eba49c93 to your computer and use it in GitHub Desktop.
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 React, { useState, useEffect } from "react"; | |
/* | |
* Check whether a page is visible to a user. | |
* Return true if it is visible to the user. Return false otherwise. | |
*/ | |
function usePageVisibility() { | |
const [isVisible, setIsVisible] = useState(getIsDocumentHidden()); | |
const onVisibilityChange = () => setIsVisible(getIsDocumentHidden()); | |
useEffect(() => { | |
const visibilityChange = getBrowserVisibilityProp(); | |
document.addEventListener(visibilityChange, onVisibilityChange, false); | |
return () => { | |
document.removeEventListener(visibilityChange, onVisibilityChange); | |
}; | |
}); | |
return isVisible; | |
} | |
/* | |
* Component1 is React function component | |
* The value of isVisible is true when a user opens this tab. When the value is false and a user opens another tab | |
* (i.e, not this tab), it is not executed. | |
*/ | |
const Component1 = () => { | |
const isVisible = usePageVisibility(); | |
useEffect(() => { | |
let timerId = setInterval(async () => { | |
if (!isVisible) clearInterval(timerId); | |
let res = await axios.get( | |
`https://api.something.com/path` | |
); | |
// Update some states, if needed | |
// Send a request every 1000ms | |
}, 1000); | |
return () => clearInterval(timerId); | |
}, [isVisible]); | |
// ... | |
return ( | |
<> | |
<div /> | |
</> | |
); | |
} | |
// References | |
// https://blog.sethcorker.com/harnessing-the-page-visibility-api-with-react | |
// https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript | |
// https://www.codingwithjesse.com/blog/detect-browser-window-focus/ | |
// https://stackoverflow.com/questions/53090432/react-hooks-right-way-to-clear-timeouts-and-intervals |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment