Perform debounce in React.js

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

    Extend useState hook

    import { useState } from "react";
    import _ from "underscore"
    export const useDebouncedState = (initialState, durationInMs = 500) => {
        const [internalState, setInternalState] = useState(initialState);
        const debouncedFunction = _.debounce(setInternalState, durationInMs);
        return [internalState, debouncedFunction];
    };
    export default useDebouncedState;
    

    Use hook

    import useDebouncedState from "../hooks/useDebouncedState"
    //...
    const [usernameFilter, setUsernameFilter] = useDebouncedState("")
    //...
     setUsernameFilter(e.target.value)}>
    

    https://trippingoncode.com/react-debounce-hook/

提交回复
热议问题