Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda