Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throttle is not working when using hooks setState

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?

like image 912
Ukasha Avatar asked Jan 20 '26 03:01

Ukasha


1 Answers

The default behaviour of lodash throttle is to run immediately and at the end of the time set (if the event is called more than once in that time). In order to get the behaviour that you want you need to pass in options to your throttle call.

const handleMouseMoveThrottle = throttle(e => {
    console.log(e.clientX, e.clientY)
    // setPosition([e.clientX, e.clientY])
  }, 1000, { leading: false }); // this says, do not run the function immediately

By default leading is set to true, the other option, trailing, is also set to true.

Check out this:

https://lodash.com/docs/4.17.11#throttle

and this:

https://github.com/lodash/lodash/blob/master/throttle.js#L52

for more information

like image 50
Brett East Avatar answered Jan 22 '26 18:01

Brett East



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!