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

191
Visualizações
Passing data from child to parent after Array State has been updated, Why am I getting an instance of the prev state?

This function is added to a button click.

  const listChangeHandler = (e) => {
    e.preventDefault();
    setIngredientList((prevArray) => [...prevArray, ingredient]);
    inputIngredient.current.value = "";

    props.data(ingredientList);
  };

Problem is: The received state (ingredientList) that I get in the parent comp is the previous, not the latest thats shown in the child component

Why and what could be the workaround?

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

0

It is due to this fact that state always updates after rerendering, so when you pass it to upper component, it still has its previous value! To solve this problem you have two solutions:

  1. update your code as follow:
const listChangeHandler = (e) => {
    e.preventDefault();
    let temp = [...ingredientList, ingredient];
    setIngredientList(temp);
    inputIngredient.current.value = "";

    props.data(temp);
  };
  1. use useRef instead of useState because in contrast to state, ref updates imediately.
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