Page lifecycle API with React custom hook


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:
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:
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:
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 for a more in-depth look on how page lifecycle works.
About the author
I am a front-end developer experienced working with React and Typescript.
So far I worked with product owners from multiple areas such as education, supply chain management, event planning, and product startups.
Before joining the front-end world, I worked as a data analyst, using Excel and Excel VBA as my daily drivers. I also had the opportunity to work as a network administrator where I learned how to build and configure Linux servers.
Comments
Join the discussionNo comments yet. Be the first to comment.





