3

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?

Ukasha
  • 2,238
  • 3
  • 21
  • 30

1 Answers1

5

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

Brett East
  • 4,022
  • 2
  • 20
  • 31
  • Can you explain this solution? I have the same issue but this option doesn't resolve it and I don't understand how it would. Thanks – Sebastian Thomas Jul 31 '19 at 16:41
  • Is it updating immediately for you @SebastianThomas? You need to pass in an options object as the third argument to throttle with `{ leading: false }` - the default it leading: true, which essentially says run the function at the leading end of the throttle, which is at 0 seconds. Also, are you using lodash? – Brett East Jul 31 '19 at 23:12
  • 1
    Hey, I am using _. It worked after I followed suggestion here: https://stackoverflow.com/a/54666498/662826 – Sebastian Thomas Aug 07 '19 at 16:30