Perform debounce in React.js

前端 未结 30 1949
礼貌的吻别
礼貌的吻别 2020-11-22 04:11

How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn\'t

30条回答
  •  无人共我
    2020-11-22 04:33

    Here's a snippet using @Abra's approach wrapped in a function component (we use fabric for the UI, just replace it with a simple button)

    import React, { useCallback } from "react";
    import { debounce } from "lodash";
    
    import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
    
    const debounceTimeInMS = 2000;
    
    export const PrimaryButtonDebounced = (props) => {
    
        const debouncedOnClick = debounce(props.onClick, debounceTimeInMS, { leading: true });
    
        const clickHandlerDebounced = useCallback((e, value) => {
    
            debouncedOnClick(e, value);
    
        },[]);
    
        const onClick = (e, value) => {
    
            clickHandlerDebounced(e, value);
        };
    
        return (
            
        );
    }
    

提交回复
热议问题