This content originally appeared on DEV Community and was authored by Anthony Oyathelemhi
TL;DR
const logoutTimerIdRef = useRef(null);
useEffect(() => {
const autoLogout = () => {
if (document.visibilityState === 'hidden') {
const timeOutId = window.setTimeout(logoutUser, 5 * 60 * 1000);
logoutTimerIdRef.current = timeOutId;
} else {
window.clearTimeout(logoutTimerIdRef.current);
}
};
document.addEventListener('visibilitychange', autoLogout);
return () => {
document.removeEventListener('visibilitychange', autoLogout);
};
}, []);
Let's take a look at what is going on in this code
- When the component that contains this code mounts, we set an event listener to watch for when the page visibility changes, i.e. when the user leaves or comes back to the tab, and calls
autoLogout
- The
autoLogout
function checks whether the page is hidden or visible - If the page is hidden, we set a timer to log the user out after 5 minutes
- If the page is visible, we clear the timer that was previously set
- We return a cleanup function to remove the event listener before the component is unmounted
For brevity, I omitted the logoutUser
function definition, which is out of the scope of this post
Why useRef
And Not useState
You can achieve the same thing with useState
, and the only reason I'm not doing that is because setting a state value causes a re-render. While this is not an issue most of the time, it can be a problem when you have some other logic that runs on every update, a la componentDidUpdate
I've put up 2 Codesandbox playgrounds to demonstrate this. The first one uses useState
and the second uses useRef
. I've set both to auto logout after 10 seconds. If you leave this page and come back, you will notice that the render count in the first one increases by one each time, but the second one remains at 1
This content originally appeared on DEV Community and was authored by Anthony Oyathelemhi
Anthony Oyathelemhi | Sciencx (2021-11-13T20:40:55+00:00) Add Auto-logout To A React App. Retrieved from https://www.scien.cx/2021/11/13/add-auto-logout-to-a-react-app/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.