I am facing a problem when using throttle. Using the code below, throttle works properly. But, something goes wrong when I uncomment setPosition([e.clientX, e.clientY])
. The throttle is broken and position
is updated immediately without waiting for 1 second.
import React, { useState } from 'react'
import { throttle } from 'lodash'
export default () => {
const [position, setPosition] = useState([0, 0])
const [x, y] = position
const handleMouseMoveThrottle = throttle(e => {
console.log(e.clientX, e.clientY)
// setPosition([e.clientX, e.clientY])
}, 1000)
const handleMouseMove = e => {
e.persist()
handleMouseMoveThrottle(e)
}
return (
<div
style={{ width: 300, height: 300, border: 'solid 1px black' }}
onMouseMove={handleMouseMove}
>
<div>
Position: {x}, {y}
</div>
</div>
)
}
Any solution?