Home > Mobile >  why my debounce event call 5 times query?
why my debounce event call 5 times query?

Time:10-21

I use lodash-debounce on input tag.

If I typed in five letters, api called 5 times.

 const onChangeInput: ChangeEventHandler = (e: any) => {
    setWords(e.target.value);
    e.target.value.length >= 2 && debounceInputChanged();
  };

  const debounceInputChanged = useMemo(
    () =>
      debounce(() => {
        searchWords();
      }, 1000),
    [words],
  );

CodePudding user response:

const onChangeInput: ChangeEventHandler = (e: any) => {
setWords(e.target.value);
e.target.value.length >= 2 && debounceInputChanged();
};

const debounceInputChanged = useMemo(
() =>
  debounce(() => {
    searchWords();
  }, 1000),
[words], // you are passing dependency over here so it's called when the word is updated.
);

CodePudding user response:

Create seperate hook for debounce like this

import { useEffect, useState } from "react";

export default function useDebounce(value: string, delay: number = 1000) {
   const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(
    () => {
      // Update debounced value after delay
      const handler = setTimeout(() => {
        setDebouncedValue(value);
      }, delay);

     return () => {
        clearTimeout(handler);
      };
    },
    [value, delay] // Only re-call effect if value or delay changes
  );

  return debouncedValue;
}

In the Component

 const debouncedSearch = useDebounce(words); // usestate variable 

  useEffect(() => {
      searchWords();

  }, [debouncedSearch]); 
  • Related