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
React setState function

What is the difference between these two state updating functions and what is the recommended approach? Both functions work fine in my application.

Option 1

const [profile, setProfile] = useState<{name: string, age: number}>({
    name: 'John Doe',
    age: 28,
  });

setProfile((prevState) => {
    return {
      ...prevState,
      age: profile.age + 100,
    }
  });

Option 2

const [profile, setProfile] = useState<{name: string, age: number}>({
    name: 'John Doe',
    age: 28,
  });

setProfile({
    ...profile,
    age: profile.age + 100,
  });
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Normally each time you want to update your state based on your previous state you should use the functional way of updating the state. It makes sure that the current state you are passing in, is the 'last version' one.

When you want to set a state based on a different value, not depending on previous state, you can set the state directly without using the functional update.

It is pretty well explained with examples in the documentation:

https://reactjs.org/docs/hooks-reference.html#usestate

the documentation includes this great example:

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

Note that unlike setState in a class component, useState doesn't merge update, Also from the documentation:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

const [state, setState] = useState({});
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

Option 2 will work in most cases because you rarely have a change of state appearing before another change of state, but it can happen in more complex cases or using useEffect or setTimeout functions and in this case the functional update is compulsory.

over 4 years ago · Santiago Trujillo Denunciar

0

They are basically the same, but the second approach is used when you can't assure that you have the updated value of your state on hand. For example in a setTimeout or useEffect callback

over 4 years ago · Santiago Trujillo 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