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

182
Visualizações
Is React Hooks SetState async?

I have a question regarding hooks and set State. Let's take very basic example. Suppose I have one input box and button, which is a very common use case. Whenever i type in input box, and click on button, button click handler should reflect the latest state. On stackoverflow, I saw below code to do the activity:

const input = props => {  
  const [textInput, setTextInput] = React.useState('');

  const handleClick = () => {
    console.log(textInput);
    props.send(textInput);
  }

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

  return (
    <div>
      <input onChange={handleChange} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
} 

Isnt above setTextInput(event.target.value); input async as react does batching? So when user clicks on submit, how do i know that state is actually updated? . This is a very basic use case and i don't want to use useRef as this must be a common problem or am i missing something?

Note: In above solution, we want to read the state only after both the conditions are satisfied:

  1. User has clicked button.
  2. State has been updated by setState
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In my limited knowledge, setState is in fact asynchronous. It does not interrupt other processes to carry out setting the state. It is queued to be executed on the next batch.

The situation you are talking about here will never have the async nature of setState cause problems. The action of the user clicking will always happen after the newState is set.

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