7

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

2
  • 1
    can you post some code? Commented Jun 14, 2019 at 12:04
  • its just functional component, where I catch onMouseEnter, and there I need to call timeout, which I need terminate (clearTimeout) in another function (onMouseLeave). I just need see how to work with timeout/cleartimeout in functional component / or with hooks Commented Jun 14, 2019 at 12:11

2 Answers 2

28

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.

Sign up to request clarification or add additional context in comments.

Comments

1

I appreciate johhny peter's answer. I had to do something similar but using useEffect to begin the setTimeout. In my case I replaced the onMouseEnter function with

  useEffect(() => {
    timerRef.current = setTimeout(onClose, duration);
    // don't forget to clean up!
    return () => clearTimeout(timerRef.current);
  }, [duration, onClose]);

and that is currently working (React 18).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.