DEV Community

How to check if a tab is active in React

Eray Kaya on July 06, 2023

Before diving into the specifics of how to detect active tab engagement, I'd like to share a real-world web3 scenario where this was a use case. Im...
Collapse
 
loucyx profile image
Lou Cyx

I recommend you use the useEffect closure instead of useCallback, and one nice improvement could be to take the document as an argument, so you can then test it with a mock object, or use proxies or anything else:

import { useEffect, useState } from "react";

export const useDocumentVisible = (documentElement = document) => {
    const [documentVisible, setDocumentVisible] = useState(
        documentElement.visibilityState,
    );

    useEffect(() => {
        const handleVisibilityChange = () =>
            setDocumentVisible(documentElement.visibilityState);

        documentElement.addEventListener(
            "visibilitychange",
            handleVisibilityChange,
        );

        return () =>
            documentElement.removeEventListener(
                "visibilitychange",
                handleVisibilityChange,
            );
    }, [documentElement]);

    return documentVisible === "visible";
};
Enter fullscreen mode Exit fullscreen mode

Cheers!