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

192
Vistas
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 Respuestas
Responde la pregunta

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