useDebounce Hook doesn't allow me to type

Viewed 298

I am trying to make a simple debouncing hook (implementation from a video) and use it in the Context but it doesn't work. More interestingly, it does not allow me to type anything in the input. I store handler functions and state in the Context and passing necessary things to child components.

useDebounce.js

import { useState } from 'react';

export default function useDebounce() {
  const [typingTimeout, setTypingTimeout] = useState('');

  function debounce(func, wait) {
    clearTimeout(typingTimeout);
    const timeout = setTimeout(() => {
      func();
    }, wait);

    setTypingTimeout(timeout);
  }

  return debounce;
}

Context API

 const [text, setText] = useState('');
 const debounce = useDebounce();

 const handleSearch = e => {
    if (e.target.value === '' || e.target.value.match(/^[0-9]+$/)) {
       debounce(() => setText(e.target.value), 1000);
    }
  };
1 Answers

The problem is in this line. When the timeout is executed the e.target.value is null/undefined. The state updates is async process and the event parameter here is a Synthetic Event and is pooled (Only relevant forReact <=16). This means that the SyntheticEvent object will be reused and all properties will be nullified after the event handler has been called.

debounce(() => setText(e.target.value), 1000);

This part setText(e.target.value) inside timeout won't work:

Change it to:

const value = e.target.value; //--> store the value
debounce(() => setText(value), 1000);
Related