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

105
Visualizações
useState is not re-rendering with push and pop on an array state

I'm attempting to update the usersData variable created using useState so that anytime someone clicks on add user, a data object is added to the beginning of usersData, but the problem is that it only works with spread operators and not with push, pop, or unshift operations, as seen in the code below.

The code below is functioning great, and it updates and re-renders every time usersData changes:

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    const dataUpdated = [data, ...usersData];
    setUsersData(dataUpdated);
  };

However, dataUpdated has the same data as above code, the following code does not re-renders the page:

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    let dataUpdated = usersData;
    dataUpdated.unshift(data);
    setUsersData(dataUpdated);
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The second attempt, which is:

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    let dataUpdated = usersData;
    dataUpdated.unshift(data);
    setUsersData(dataUpdated);
  };

does not re-render because for React nothing has changed, since you are giving the same reference to setUsersData. In fact unshift updates the content without affecting the reference, therfore dataUpdated === usersData.

Every time you need to update an Object or an Array to have a re-render, you need to create a new reference. And the spread operator does that, and this is why your first attempt is working, which is:

const [usersData, setUsersData] = useState([]);

  const receiveUserData = (data) => {
    const dataUpdated = [data, ...usersData];
    setUsersData(dataUpdated);
  };
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