I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I\'m not able to figure out
Just built this using hooks as of React 16.8
import React, { useEffect } from 'react';
// User has switched back to the tab
const onFocus = () => {
console.log('Tab is in focus');
};
// User has switched away from the tab (AKA tab is hidden)
const onBlur = () => {
console.log('Tab is blurred');
};
const WindowFocusHandler = () => {
useEffect(() => {
window.addEventListener('focus', onFocus);
window.addEventListener('blur', onBlur);
// Specify how to clean up after this effect:
return () => {
window.removeEventListener('focus', onFocus);
window.removeEventListener('blur', onBlur);
};
});
return <>>;
};
export default WindowFocusHandler;