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

143
Visualizações
React, component not re-rendering after change in an object state

There are others Stack Overflow threads that are kind of related to this question but vaguely titled or briefly answered. So I wanted to create one that would more explicitly and simply resolve the problem that occurs when changing a state that's an object.

Notice I'm updating on click the firstName property of user object, which is a state and nothing is happening. Here is the code:

const App = () => {
  const [user, setUser] = React.useState({ firstName: "Jhon", lastName: "Doe", tel:"09004345000" });
  const changeFirstAndLastName = () => {
    const newUser = user;
    newUser.firstName = "David";
    setUser(newUser);
  };
  return (
    <div>
      <div>
        <p>First Name: {user.firstName}</p>
        <p>Last Name: {user.lastName}</p>
        <p>Tel: {user.tel}</p>
      </div>
      <button onClick={changeFirstAndLastName}>
        Change First Name
      </button>
    </div>
  );
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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

0

React won't re-render because it's like nothing has changed, that is every time you give the same state to a setState. For primitive values like Number, String, and Boolean, it's obvious to know wether we are giving a different value or not.

For referenced values like Object and Array in the other hand, changing their content doesn't flag them as different. It should be a different memory reference. See your commented code to understand what you are doing wrong:

const newUser = user;         // will do a reference copy => newUser == user
newUser.firstName = "David"; // will change its content => newUser == user
setUser(newUser);           // at this point it's like nothing has changed

A solution could be the spread operator, will create a copy of your existing object but on a new memory reference, and then you overwrite the properties that you want to change:

setUser({...user, firstName: "David"}); 

Find fully working example below:

const App = () => {
  const [user, setUser] = React.useState({ firstName: "Jhon", lastName: "Doe", tel:"09004345000" });
  const changeFirstAndLastName = () => {
    setUser({...user, firstName: "David"}); 
  };
  return (
    <div>
      <div>
        <p>First Name: {user.firstName}</p>
        <p>Last Name: {user.lastName}</p>
        <p>Tel: {user.tel}</p>
      </div>
      <button onClick={changeFirstAndLastName}>
         Change First Name
      </button>
    </div>
  );
}
ReactDOM.render(
    <App />,
    document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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