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?
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:
const listChangeHandler = (e) => {
e.preventDefault();
let temp = [...ingredientList, ingredient];
setIngredientList(temp);
inputIngredient.current.value = "";
props.data(temp);
};
useRef instead of useState because in contrast to state, ref updates imediately.