DEV Community

Cover image for Add Auto-logout To A React App
Anthony Oyathelemhi
Anthony Oyathelemhi

Posted on

Add Auto-logout To A React App

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);
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Let's take a look at what is going on in this code

  1. 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
  2. The autoLogout function checks whether the page is hidden or visible
  3. If the page is hidden, we set a timer to log the user out after 5 minutes
  4. If the page is visible, we clear the timer that was previously set
  5. 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)

Collapse
 
akwasin profile image
akwasin

This looks solid but wouldnt it be much better if addEventListener listed to an array of events such ass mousemove, mouseup/down, click maybe even keypress instead of visibilitychange?

Collapse
 
jsyme222 profile image
Justin Syme • Edited

Super slick, I'm happy for the useRef usage. I would take this one step further and create a custom useAutoLogout hook for reuse.

Collapse
 
frontendtony profile image
Anthony Oyathelemhi

Greate idea Justin. Custom hooks just makes code super clean and more readable

Collapse
 
ndukachukz profile image
ndukachukz

Great. I also understood the cleanup method in useEffect

Collapse
 
ecj222 profile image
Enoch Chejieh

Very intuitive.

Collapse
 
frontendtony profile image
Anthony Oyathelemhi

Thank you Enoch