skip to Main Content

i follow this link to handle input:

  const handleSearch = useMemo(() => {
    _.debounce(text => {
      console.log(text);
    });
  }, []);

  const handleOnSearch = useCallback(
    text => {
      handleSearch(text);
    },
    [handleSearch],
  );

but i get error: handleSearch is not a function (this error only trigger when i enter text into the input)

But if i use this code, everything ok:

  const handleSearch = useRef(
    _.debounce(over => {
      console.log(over);
    }, 1000),
  );

  const handleOnSearch = useCallback(text => {
    setTextSearch(text);
    handleSearch.current(text);
  }, []);

Can someone explain to me please?

2

Answers


  1. You are not returning the value from _.debounce so handleSearch gets undefined

      const handleSearch = useMemo(() => {
        return _.debounce(text => {    // use return here
          console.log(text);
        });
      }, []);
    

    useMemo returns the value from the callback, passed to it as argument. And your callback does not return anything.

    You can do it like this as well, the same as using useRef:

       const handleSearch = useCallback(
        _.debounce(text => {
          console.log(text);
      }), []);
    

    But here _.debounce will execute on each render

    Login or Signup to reply.
  2. useMemo is expecting a callback and it will return the callback result.
    its purpose is to cache the result so the callback doesn’t need to be re-run every time the component is rendered.

    So since the callback sent to useMemo doesn’t return a value, handleSearch is undefined. this is how you fix it:

    const handleSearch = useMemo(() => {
        return _.debounce(text => {
            console.log(text);
        });
    }, []);
    
    const handleOnSearch = useCallback(
       text => {
           handleSearch(text);
       }, [handleSearch]);
    

    however – I don’t see much purpose is the way you are combining useMemo and useCallback, since the handleSearch never changes, and handOnSearch only calls handleSearch.
    Therefore, you can reduce them to a single useMemo (you can use useCallback but I think this is slightly more readable):

    const handleSearch = useMemo(() => {
        return _.debounce(text => console.log(text));  
    }, []);
    

    and then whenever you use handleOnSearch just use handleSearch

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search