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);
// Calls onFocus when the window first loads
onFocus();
// Specify how to clean up after this effect:
return () => {
window.removeEventListener("focus", onFocus);
window.removeEventListener("blur", onBlur);
};
}, []);
return <></>;
};
export default WindowFocusHandler;
EDIT May 2023:
There is a new visibilitychange event that has more nuanced behavior for mobile web tabbing. If you need different behavior for when mobile users are viewing their web tabs vs having switched to a different tab you can use that event api as described in more answers below.