Perform debounce in React.js

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

    FYI

    Here is another PoC implementation:

    • without any libraries (e.g. lodash) for debouncing
    • using React Hooks API

    I hope it helps :)

    import React, { useState, useEffect, ChangeEvent } from 'react';
    
    export default function DebouncedSearchBox({
      inputType,
      handleSearch,
      placeholder,
      debounceInterval,
    }: {
      inputType?: string;
      handleSearch: (q: string) => void;
      placeholder: string;
      debounceInterval: number;
    }) {
      const [query, setQuery] = useState('');
      const [timer, setTimer] = useState();
    
      useEffect(() => {
        if (timer) {
          clearTimeout(timer);
        }
        setTimer(setTimeout(() => {
          handleSearch(query);
        }, debounceInterval));
      }, [query]);
    
      const handleOnChange = (e: ChangeEvent): void => {
        setQuery(e.target.value);
      };
    
      return (
        
      );
    }
    

提交回复
热议问题