'throttle from lodash in react not working
I use the throttle from lodash in this way on mouseMove event to track the mouse position in the div square, but the throttle function that I wrote seems not working. where I am wrong?
import React, { useState } from "react";
import "./index.css";
import _throttle from "lodash/throttle";
function Throttle() {
const [state, setState] = useState({
clientX: 0,
clientY: 0
});
const update = ({ clientX, clientY }) => {
setState({ clientX, clientY });
};
const throtteFn = _throttle(update, 1000);
const handleMouseMove = (event) => {
event.persist();
throtteFn(event);
};
return (
<>
<div
style={{
width: "10em",
backgroundColor: "green",
height: "10em"
}}
onMouseMove={handleMouseMove}
/>
<div>
<p>clientX: {state.clientX}</p>
<p>clientY: {state.clientY}</p>
</div>
</>
);
}
export default Throttle;
Solution 1:[1]
You need to consider the position of the rectangle in the viewport. Keep a ref to get the left and top positions of the rectangle.
Try like this
const ref = useRef();
const update = ({ clientX, clientY }) => {
const { top, left } = ref.current.getBoundingClientRect();
// deduct the left and top offset values before setting the values
setState({
clientX: clientX - left >= 0 ? clientX - left : 0,
clientY: clientY - top >= 0 ? clientY - top : 0
});
};
...
...
<>
<div
style={{
width: "10em",
backgroundColor: "green",
height: "10em"
}}
onMouseMove={handleMouseMove}
ref={ref}
/>
...
...
</>
Solution 2:[2]
You must use usecallback in the throttle function. For now, throttleFn is constantly being created so it doesn't work the way you want it to.
const throtteFn = useCallback(_throttle(update, 1000), []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amila Senadheera |
Solution 2 | pruge |