reactjstypescriptfunctional-programmingtimeout

How to do timeout and then clear timeout in react functional component?


Hi,

I have functional component in reactjs, and I am trying to do timeout on mouse hover over menu, which is fine and work well, but I dont know how to clear this timeout in other function in this same functional component, is there some solution for this? I primary use hooks. I found some hooks timeout, but not work well. Thanks very much


Solution

  • You can use something like this.

    import React, { useRef } from 'react';
    
    const Menu = () => {
      const timerRef = useRef(null);
    
      const onMouseEnter = () => {
        timerRef.current = setTimeout(() => {}, 1000);
      }
    
      const onMouseLeave = () => {
        if(timerRef.current) {
          clearTimeout(timerRef.current);
        }
      }
    
      return <div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} />
    }
    

    What's happening here is that, we are saving the timer's reference in a react ref. This can then be used to check and clear the timer in another function.