Perform debounce in React.js

前端 未结 30 1619
礼貌的吻别
礼貌的吻别 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:34

    This solution does not need any extra lib and it also fires things up when the user presses enter:

    const debounce = (fn, delay) => {
        let timer = null;
        return function() {
            const context = this,
            args = arguments;
            clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        };  
    }
    
    const [search, setSearch] = useState('');
    const [searchFor, setSearchFor] = useState(search);
    
    useEffect(() => {
        console.log("Search:", searchFor);
    }, [searchFor]);
    
    const fireChange = event => {
        const { keyCode } = event;
        if (keyCode === 13) {
            event.preventDefault();
            setSearchFor(search);
        }
    }
    
    const changeSearch = event => {
        const { value } = event.target;
        setSearch(value);
        debounceSetSearchFor(value);
    };
    
    const debounceSetSearchFor = useCallback(debounce(function(value) {
        setSearchFor(value);
    }, 250), []);
    

    and the input could be like:

    
    

提交回复
热议问题