简体   繁体   中英

How to throttle/debounce function inside of React useEvent hook?

Note that useEvent is still in the proposal stage, but is available for use today through the react-use-event-hook package.


Unfortunately it doesn't seem like it's possible to properly throttle a function inside of useEvent , but I'd really like to be shown that I'm wrong.

I guess we need to throttle the function somewhere else? But then if we need to do that from the same functional component, then useEvent is pretty grievously limited.

How about something like this:

export const useThrottledEvent = <T extends (...args: never[]) => unknown>(
  callback: T,
  delay: number,
): T => {
  const event = useEvent(callback)
  return useCallback(throttle(event, delay), [event, delay])
}

I haven't been able to test @thedude's answer but it reminded me to share the solution we eventually settled on:

const OurComponent = ({ children, handler }) => {
  const someArg = 1;

  const throttledHandler = useCallback(
    _throttle(handler, 450, { leading: false, trailing: true }), // Leading/trailing are presumably not required to be set
    [handler]
  );

  const onKeyDown = useEvent(evt => {
    throttledHandler.cancel();
    
    // ... Your logic here - eg:
    throttledHandler(someArg)
  });

  return <span>{children}</span>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM