[React] Detect user activity with a custom useIdle React Hook

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Detect user activity with a custom useIdle React Hook相关的知识,希望对你有一定的参考价值。

If the user hasn‘t used your application for a few minutes, you may want to log them out of the application automatically in case they‘ve stepped away from the machine and someone nefarious attempts to use their session. Let‘s checkout how you can create a custom React hook that wraps a regular npm module called activity-detector to solve this problem.

 

import React from "react";
import ReactDOM from "react-dom";
import createActivityDetector from "activity-detector";

import "./styles.css";

function useIdle(options) {
  const [isIdle, setIsIdle] = React.useState(false);
  React.useEffect(() => {
    const activityDetector = createActivityDetector(options);
    activityDetector.on("idle", () => setIsIdle(true));
    activityDetector.on("active", () => setIsIdle(false));

    // clean the subscription
    return () => {
      activityDetector.stop();
    };
  });
  return isIdle;
}

function App() {
  const isIdle = useIdle({ timeToIdle: 1000 });
  return (
    <div className="App">
      {!isIdle ? <div>Hello World</div> : <div>Are you there?</div>}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

UseEffect

 

 

以上是关于[React] Detect user activity with a custom useIdle React Hook的主要内容,如果未能解决你的问题,请参考以下文章

hexo d错误:fatal: unable to auto-detect email address

markdown Rails + React build + Active Storage资产

如何从 React Native Android 模块访问 Activity?

致命错误:在第 177 行调用 C:\Users\Jarek\mywebsite\phpMyAdmin\libraries\php-gettext\gettext.inc 中未定义的函数 mb_det

React Native 中的 Android Activity 生命周期 - ViewPager

无法访问 discord.js 中的 user.presence.activities