oderfla
oderfla

Reputation: 1797

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?

Upvotes: 5

Views: 6504

Answers (2)

Mykyta Khmel
Mykyta Khmel

Reputation: 11

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

Upvotes: 1

eilonmore
eilonmore

Reputation: 119

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

Upvotes: 7

Related Questions