xnimorz/use-debounce

add "isPending" to the useDebouncedCallback

Closed this issue · 4 comments

capaj commented

it would be nice if https://github.com/xnimorz/use-debounce#callpending-method also returned isPending.
Also since it would return 4 items now, it might make sense to change it into an object. Destructuring an object is fair bit nicer than an array of four items.

Hi @capaj, Thank you for the issue.

Talking about isPending:

Returning isPending from useDebouncedCallback will lead to unnecessary component rerender. (as it will be required to include isPending not as an instance ref, but as a part of the hook state).
Also, isPending could be implemented outside useDebouncedCallback without any difficulties.

So, it seems that we will deoptimize useDebouncedCallback if we include isPending.

Of course, we are able to add an additional param to the hook, which could turn on isPending. You are welcome to open a PR with such param!

Talking about changing the array to an object: it's a good idea, but it requires a major release, so that, we'll make this change as soon as any additional breaking changes will be released.

isPending could be implemented internally in V4 pretty easily

  const pending = useCallback(() => {
    return timerId.current !== undefined;
  }, []);

Talking about changing the array to an object: it's a good idea, but it requires a major release, so that, we'll make this change as soon as any additional breaking changes will be released.

I've been using a fork of useDebounce at work. Decided to do like like lodash and return the debounced callback but attach the other functions to it:

// useDebouncedCallback.tsx

const cancel = useCallback(() => {...});
const flush = useCallback(() => {...});
const pending = useCallback(() => {...});
const debounced = useCallback(() => {...});

debounced.cancel = cancel;
debounced.flush = flush;
debounced.pending = pending;
return debounced;


// MyComponent.tsx

const debounced = useDebouncedCallback(() => {...}, 500);

useEffect(() => {
  if (shouldFlush) {
    debounced.flush();
  }
}, [shouldFlush])

useEffect(() => debounced.cancel, [])

return <button onClick={debounced}>click me</button>

Might be one route this lib could go down.

Hi @capaj !

Published in use-debounce@5.0.0
The full changelog is here: https://github.com/xnimorz/use-debounce/blob/master/CHANGELOG.md#500
The example of using pending is on unit tests: 1b4ac04#diff-f19398ad88ba687dc4ddd6887f3ed8f8R652-R664

Also, please take note, that the returning value from useDebouncedCallback and useDebounce was changed: https://github.com/xnimorz/use-debounce/blob/master/src/useDebouncedCallback.ts#L9-L23 (BTW it's also mentioned in changelog)

capaj commented

Thanks. This is great. Closing!