Add Auto-logout To A React App

Add Auto-logout To A React App

Learn how to correctly implement auto-logout logic in React


const logoutTimerIdRef = useRef(null);

useEffect(() => {
  const autoLogout = () => {
    if (document.visibilityState === 'hidden') {
      const timeOutId = window.setTimeout(logoutUser, 5 * 60 * 1000);
      logoutTimerIdRef.current = timeOutId;
    } else {

  document.addEventListener('visibilitychange', autoLogout);

  return () => {
    document.removeEventListener('visibilitychange', autoLogout);
}, []);

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