Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!