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

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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