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

118
Vistas
When to use functional update form of useState() hook, eg. setX(x=>x+1)

Normally when we need to update a state in a functional component, we do something like this:

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(count + 1)}>
                    Click me
                 </button>
            </div>);
}

When and why will we ever need to use the functional update form?

function Example() {
    const [count, setCount] = React.useState(0);
    return (<div><p>You clicked {count} times</p>
                 <button onClick={() => setCount(c=>c + 1)}>
                    Click me
                 </button>
            </div>);
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Use the function form when the setter may close over an old state value.

For example, if an async request is initiated, and you want to update state after that's done, the request that was made will have scope of the state as it was at the beginning of the request, which may not be the same as the most up-to-date render state.

You may also need to use the function form if the same state value was just updated, eg

setValue(value + 1);
// complicated logic here
if (someCondition) {
  setValue(value => value + 1);
}

because the second call of setValue closes over an old value.

about 4 years ago · Juan Pablo Isaza Denunciar

0

State Updates May Be Asynchronous:

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

useState is the same as setState in this condition.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can see the different when call set state twice:

<button
  onClick={() => {
    setCount(count + 1);
    setCount(count + 1);
  }}
></button>;

<button
  onClick={() => {
    setCount(c => (c + 1));
    setCount(c => (c + 1));
  }}
></button>;
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