Delay React onMouseOver event
Here's a way you can delay your event by 500ms using a combination of onMouseEnter
, onMouseLeave
, and setTimeout
.
Keep in mind the state update for your data could be managed by a parent component and passed in as a prop.
import React, { useState } from 'react'const ListElement = () => { const [data, setData] = useState(null) const [delayHandler, setDelayHandler] = useState(null) const handleMouseEnter = event => { setDelayHandler(setTimeout(() => { const yourData = // whatever your data is setData(yourData) }, 500)) } const handleMouseLeave = () => { clearTimeout(delayHandler) } return ( <div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > I have a delayed event handler </div> )}export default ListElement
You can use debounce
as a dedicated package or get it from lodash
, etc:
Useful for implementing behavior that should only happen after a repeated action has completed.
const debounce = require('debounce');class YourComponent extends Component { constructor(props) { super(props); this.debouncedMouseOver = debounce(handleMouseOver, 200); } handleMouseOver = data => this.setState({ data }); render() { const data = []; return <ListElement onMouseOver={() => this.debouncedMouseOver(data)}>Data</ListElement>; }}
You can create a method that will trigger the onMouseOver
event when matching special requirements.
In the further example, it triggers after 500 ms
.
/** * Hold the descriptor to the setTimeout */protected timeoutOnMouseOver = false;/** * Method which is going to trigger the onMouseOver only once in Xms */protected mouseOverTreatment(data) { // If they were already a programmed setTimeout // stop it, and run a new one if (this.timeoutOnMouseOver) { clearTimeout(this.timeoutOnMouseOver); } this.timeoutOnMouseOver = setTimeout(() => { this.setState(data); this.timeoutOnMouseOver = false; }, 500);}