0

I have a react application and in that I need to check whether the app is on idle or no user interaction. I currently use the document.hasFocus() method every 5 seconds to check if the page is focus and if it is not focus I simply alert the user using window.alert as shown in the following code.

import { useEffect } from 'react';


function App() {

useEffect(() => {
setInterval(() => {
  document.hasFocus() ? console.log('focused') : window.alert("Pls reload")
}, 5000);
}, [])


  return (
    <div className="App">
  Some content
    </div>
  );
}

export default App;

But the above code only works if the page is not focus but it wont do anything if the page is on focus and user is idle for few minutes or if there aren't any user interaction for few minutes.

What I want is even if the page is focused or not, if the user is idle or there aren't any user interaction with the app, I simply want to alert the user and reload the page. Is there a way in react to achieve this?

Minsaf
  • 234
  • 2
  • 11
  • 1
    Generally you will listen for interactive events (mouse move, keypresses, pointer events, etc....) and if none happen in a certain timeframe then consider the user idle. – Drew Reese May 18 '22 at 05:55
  • 1
    I used `react-idle-timer` to get events when user idles. Visit https://www.npmjs.com/package/react-idle-timer – Julius0505 May 18 '22 at 06:03

0 Answers0