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

140
Visualizações
What's the difference between passing a value and passing a callback in a React setState hook function?

Let say I declare a local state using React hook useState() :

const [count, setCount] = useState(0);

Later I would like to update the state and trigger the re-rendering:

  1. Set the state by passing the value
<button onClick={() => setCount(count+1)}
  1. Set the state by passing a callback
<button onClick={() => setCount((prev_count) => prev_count+1)}

What is the difference between these 2 types of update?

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

0

Here it does not make any difference but once your application grows bigger and you have count used at many places, there is a possibility that multiple setState calls would be happening and queuing up data to be rendered to the DOM, and hence the actual value of count might not be what you think.

This is exactly why it is recommended to use the previous state in the callback. prevState is always a reliable solution without tracing every state update to know what the count is.

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Passing a callback will provide you the access to current state via callback function argument setCount((curr_count) => curr_count+1) .
  2. If your state updates are batched , using the state value in setCount(count+1) will provide you the stale state, chances are there that you might access the previous state.
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