Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
SetTimeOut in React hook does not allow writing to input text

I'm trying to wait 2 seconds when an input text contains text and make a request to my API. I wrote this function as a react hook called useBounce:

const useDebounce = (func, milliseconds) => {
    const time = milliseconds || 400
    let timer
    return event => {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(func, time, event)
    }
}

export default useDebounce

So I have an input with an onChange that when I try to write react it doesn't allow me to do it and the call function to my API doesn't execute:

 const searchDebounce = useDebounce((e) => {
     setInput(e.target.value);
        e.preventDefault()
        console.log(e.target.value)
    }, 2000) 

  return (
    <>
      <input
        type="text"
        onChange={ searchDebounce }
        value={input}
        className='border-2 border-cyan-500'
      />
    </>
  )

For now I am trying to see what is written in the input through the console but since it does not allow me to write, the console is blank.

Thanks for your help.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

it works with your code with minor changes, i dont know the exact why tho

const useDebounce = (func, milliseconds) => {
  const time = milliseconds || 400;
  let timer;
  return (event) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(func, time, event.target?.value);
  };
};

const [input, setInput] = useState('');

const searchDebounce = useDebounce((e) => {
  setInput(e);
}, 2000);


  return (
    <>
      <input
        type="text"
        onChange={searchDebounce}
        className="border-2 border-cyan-500"
      />
    </>
  );

the thing is, if you want to implement debounce function to search something by your input, you shouldn't debounce the the function to update input state (setInput), since it will also delay the text input value when user is typing in.

about 4 years ago · Juan Pablo Isaza Relatório

0

Below is the example for same

const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value]);

  return debouncedValue;
};

the above is my custom useDebounce hook and to delay the input check below code

export const Debouncing = () => {
  const [value, setValue] = useState("");
  const delayedValue= useDebounce(value, 2000);

 // useEffect(()=>{
  //apiCall()  api call goes here
  //},[delayedValue]);

  return (
    <>
      <h1>Debouncing</h1>
      Current: {value} - Debounced: {delayedValue}
      <input
        value={value}
        onChange={(e) => setValue(e.target.value)}
        style={{ margin: "30px" }}
        placeholder="input search"
      />
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda