How to use throttle or debounce with React Hook?

后端 未结 17 994
甜味超标
甜味超标 2020-11-30 04:27

I\'m trying to use the throttle method from lodash in a functional component, e.g.:

const App = () => {
  const [value, setValue         


        
17条回答
  •  隐瞒了意图╮
    2020-11-30 04:58

    Here's a simple hook to debounce your calls.

    To use the below code, all you have to do is declare it as so

    const { debounceRequest } = useDebounce(someFn);

    And, then call it as so

    debounceRequest(); 
    

    Implementation is shown below

    import React from "react";
    
    const useDebounce = (callbackFn: () => any, timeout: number = 500) => {
    const [sends, setSends] = React.useState(0);
    
    const stabilizedCallbackFn = React.useCallback(callbackFn, [callbackFn]);
    
    const debounceRequest = () => {
      setSends(sends + 1);
    };
    
    // 1st send, 2nd send, 3rd send, 4th send ...
    // when the 2nd send comes, then 1st set timeout is cancelled via clearInterval
    // when the 3rd send comes, then 2nd set timeout is cancelled via clearInterval
    // process continues till timeout has passed, then stabilizedCallbackFn gets called
    // return () => clearInterval(id) is critical operation since _this_ is what cancels 
    //  the previous send.
    // *

提交回复
热议问题