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
Top comments (6)
This looks solid but wouldnt it be much better if
addEventListener
listed to an array of events such assmousemove, mouseup/down
, click maybe even keypress instead ofvisibilitychange
?Super slick, I'm happy for the
useRef
usage. I would take this one step further and create a customuseAutoLogout
hook for reuse.Greate idea Justin. Custom hooks just makes code super clean and more readable
Great. I also understood the cleanup method in useEffect
Very intuitive.
Thank you Enoch