This works:
const addGoalHandler = () => {
setCourseGoals(currentGoals => [...currentGoals, enteredGoal]);
};
But this way it works differently:
const addGoalHandler = () => {
let arrGoals = courseGoals;
arrGoals.push(enteredGoal);
setCourseGoals(arrGoals);
};
Both methods are supposed to add the content of the input into an array, and then this array should be rendered as a list. The first does, but the second only renders the list when the value of the input changes. Any idea why that happens?
This happens because the "setState" function handles asynchronous actions, in turn React bundles multiple setState() calls into a single update to improve performance. This means that setState does not immediately mutate the state of your component. You can review this information in the "State and lifecycle" documentation of a React component at the following link State and lifecycle
Within the best practices to mutate your state, I recommend you to continue using the spread operator or use the concat function of the arrays.
Another important point that I would like to mention is that if you are going to take into account the previous state to update your state, you should always use the value returned by the setState callback function.