# Page lifecycle API with React custom hook

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1701427814395/64edada1-6fbf-4111-8fdc-6bfd7ae9ae8a.jpeg align="center")

The web application my team is building needs the users to be logged in, to be able to edit the content. The login is a token-based system with a short expiration time and the app is built using React JS.

As you can imagine, users sometimes leave the page open on the browser for several minutes, maybe hours. When they come back to the page, it can happen so that the token expired, but the user doesn't know it yet. He will find out only after making a request.

We needed a way to check if the token is valid every time the user returned to the page. Polling was one way to accomplish this, that is simply hitting an API endpoint to check validity at a set interval of time. But that seems like a lot of unnecessary requests for a simple token check.

### **Observing page states**

It is possible to run JavaScript code that determines the current page state from the existing web platform APIs:

```javascript
const getState = () => {
  if (document.visibilityState === 'hidden') {
    return 'hidden';
  }
  if (document.hasFocus()) {
    return 'active';
  }
  return 'passive';
};
```

### **The hook**

One elegant way to check the page state is using a React hook. Inside the hook, we can have an effect which will run on every page state change:

```javascript
useEffect(() => {
  // Set the next state
  const visibilityChange = () => {
    setPageState(getState());
  };
  // These  events can all use the same listener to observe state
  // changes (they call the `getState()` function to determine the next state).
  ['focus', 'blur', 'visibilitychange', 'resume'].forEach(type => {
    window.addEventListener(type, visibilityChange, {
      capture: true,
    });
  });
  //Every next effect we need to remove the previous listeners
  return () => {
    ['focus', 'blur', 'visibilitychange', 'resume'].forEach(type => {
      window.removeEventListener(type, visibilityChange);
    });
  };
});
```

The above code does two things:

* Sets the pageState using the `getState()` function.
    
* Adds capturing event listeners for all necessary page events
    

### **The usePageVisibility hook**

And here we have the complete `usePageVisibility` code:

```javascript
import { useState, useEffect } from 'react';

const getState = () => {
  if (document.visibilityState === 'hidden') {
    return 'hidden';
  }
  if (document.hasFocus()) {
    return 'active';
  }
  return 'passive';
};

export const usePageVisibility = () => {
  const [pageState, setPageState] = useState(getState());

  useEffect(() => {
    const visibilityChange = () => {
      setPageState(getState());
    };
    //add listeners
    ['focus', 'blur', 'visibilitychange', 'resume'].forEach(type => {
      window.addEventListener(type, visibilityChange, {
        capture: true,
      });
    });
    //cleanup
    return () => {
      ['focus', 'blur', 'visibilitychange', 'resume'].forEach(type => {
        window.removeEventListener(type, visibilityChange);
      });
    };
  });
  return pageState;
};
```

Now every time you leave and come back to the page, the `setTokenExpired()` will be triggered and update the component state.

### **Conclusion**

Sometimes you need a simple way to check if a user is still logged in. With React Hooks, and especially the ability to put together custom Hooks, creating a reusable Hook to serve just such a purpose seemed inevitable.

Check [this article](https://developers.google.com/web/updates/2018/07/page-lifecycle-api) for a more in-depth look on how page lifecycle works.
