How to add a delay onMouseOver event handler with React?

Sometimes, we want to add a delay onMouseOver event handler with React.

In this article, we’ll look at how to add a delay onMouseOver event handler with React.

How to add a delay onMouseOver event handler with React?

To add a delay onMouseOver event handler with React, we can use the Lodash debounce function.

For instance, we write:

import React, { useState } from "react";
import { debounce } from "lodash";

export default function App() {
  const [isHovered, setIsHovered] = useState(false);
  console.log(isHovered);

  const debouncedHandleMouseEnter = debounce(() => setIsHovered(true), 500);

  const handlOnMouseLeave = () => {
    setIsHovered(false);
    debouncedHandleMouseEnter.cancel();
  };

  return (
    <div
      onMouseEnter={debouncedHandleMouseEnter}
      onMouseLeave={handlOnMouseLeave}
    >
      hover me
    </div>
  );
}

We defined the isHovered state with useState.

Then we define the debouncedHandleMouseEnter function by passing in the event handler function into Lodash’s debounce function.

We set the debounce delay to 500ms.

Next, we have the handlOnMouseLeave function where we call debouncedHandleMouseEnter.cancel to cancel the calling of the debouncedHandleMouseEnter function when handlOnMouseLeave is called.

Therefore, when we hover over the div, we see isHovered becomes true.

And when we move our mouse away from the div, isHovered becomes false.

Conclusion

To add a delay onMouseOver event handler with React, we can use the Lodash debounce function.