Search code examples
javascriptreactjsreact-hookslodash

Using Lodash debounce with React useCallback for input onChange event


I'm trying to debounce an onChange event when a user type in a input field.

I'm referencing these threads:

I have the following snippet where I try to replicate the solutions provided in the threads above:

const handler = useCallback(debounce(setSearchQuery(value), 500), []);

useEffect(() => {
  document.addEventListener('keydown', handleDocumentKeyDown);
  handler(value);
  return () => document.removeEventListener('keydown', handleDocumentKeyDown);
}, [isOpen, handleDocumentKeyDown, handler, value]);

// ...

const handleChange = (event) => {
  setValue(event.target.value);
};

Error:

Uncaught TypeError: handler is not a function

How can I debounce setSerachQuery() for 500ms while the user is typing in the input field?


Solution

  • The issue in your case is that instead of passing a function to debounce, you are invoking it directly. You can use arrow function within debounce like

    const handler = useCallback(debounce(() => setSearchQuery(value), 500), []);
    

    Full code

    const handler = useCallback(debounce(() => setSearchQuery(value), 500), []); // arrow function here
    
      useEffect(() => {
        document.addEventListener('keydown', handleDocumentKeyDown);
        handler(value);
        return () => document.removeEventListener('keydown', handleDocumentKeyDown);
      }, [isOpen, handleDocumentKeyDown, handler, value]);
    
      ...
    
      const handleChange = (event) => {
        setValue(event.target.value);
      };