'How to rerun useEffect when page is visible?

A react app using hooks. In useEffect there is an api-call to populate content on page. Each element fetched is clickable. And a click will open details for the clicked element in a new browser window/tab.

When working in the new window, the user can make changes on that object. The user will then close that tab or at least just go back to the main window/tab.

Question is how I can detect that the user is coming back to the main window. This is because I want to re-fetch data from API. Thus, I want to rerun useEffect. While googling I found this:

https://www.npmjs.com/package/react-page-visibility

Is that really what I'm looking for? Reading the docs I'm not really sure if that can be the solution to my issue. Is there another way to solve this?



Solution 1:[1]

You can use the visibilitychange event to achieve that:

const onVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    console.log("Tab reopened, refetch the data!");
  }
};

useLayoutEffect(() => {
  document.addEventListener("visibilitychange", onVisibilityChange);

  return () => document.removeEventListener("visibilitychange", onVisibilityChange);
}, []);

Codesandbox

Solution 2:[2]

With React 18 you can use 'visibilitychange' with react brand new hook useSyncExternalStore

export function useVisibilityChange(serverFallback: boolean) {
  const getServerSnapshot = () => serverFallback;
  const [getSnapshot, subscribe] = useMemo(() => {
    return [
      () => document.visibilityState === 'visible',
      (notify: () => void) => {
        window.addEventListener('visibilitychange', notify);

        return () => {
          window.removeEventListener('visibilitychange', notify);
        };
      },
    ];
  }, []);

Gist with hook

P.S:Don't forget cross-browser usage

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eilonmore
Solution 2 Mykyta Khmel