score:1

Accepted answer
const timerId = useRef(null)

  const myFunc = () => {
    clearTimeout(timerId.current)
    timerId.current = null
    console.log('DO SOMETHING')
  }

  const onDocumentClick = () => {
    if (timerId.current) {
      clearTimeout(timerId.current)
      timerId.current = window.setTimeout(myFunc, 3000)
    }
  }

  useEffect(() => {
    timerId.current = window.setTimeout(myFunc, 3000)

    document.addEventListener('click', onDocumentClick)
    return () => {
      clearTimeout(timerId.current)
      document.removeEventListener('click', onDocumentClick)
    }
  }, [])

score:0

let timerId;

function Device() {
  const logOutUser = () => {
   // log out code...
  };

  const startTimer = () => {
    if (timerId) clearTimeout(timerId); 
    timerId = setTimeout(logOutUser, 3000);
  }

  const stopTimer = () => clearTimeout(timerId);

  useEffect(() => {
    // start timer when component is mounted
    startTimer();

    // stop timer when component is unmounted
    return stopTimer;
  }, []);


  return <div onClick={startTimer}></div>;
}

Related Query

More Query from same tag