Skip to content

Instantly share code, notes, and snippets.

@jyoo
Last active May 7, 2021 16:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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