xnimorz / use-debounce

A debounce hook for react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support lodash style throttling options for trailing+maxWidth

tryggvigy opened this issue · comments

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

It would be nice to be able to do this:

useDebouncedCallback(callback, 300, {
  leading: true,
  trailing: false,
  maxWait: 300,
}),

where the trailing edge is turned off.
Let's say the function is called twice in the first 300ms.

What happened
Debounced function is called twice even though trailing is false (this is due to the maxWait logic).

What I would have expected
Debounced function to have been called once.

From Debouncing and Throttling Explained Through Examples which is linked in lodash source:

The new maxWait option (only in Lodash at the moment) is not covered in this article but it can be very useful. Actually, the throttle function is defined using _.debounce with maxWait, as you see in the lodash source code.

I think we'd need to keep track of calls with Date.now() and compare agains maxWait to achieve this behaviour.
This is what lodash debounce does.

commented

Hi @tryggvigy
Good point, you are welcome to open a PR, or I'll make these changes later when I would have free time.

fixed in #62

commented

Published use-debounce@4.0.0