I’m working on State Hook, where we are adding objects to an array (https://www.codecademy.com/courses/react-101/lessons/the-state-hook/exercises/arrays-in-state).
I noticed that the code below adds an object to an array by setState.
const addItem = (item) => {
setCart((prev)=>{
return [item, ...prev];
})
};
But i’m wondering why return
is inside the setCart
function, while it seems more logical to return the entire setCart
to addItem.
I got confused because in the previous lesson, I learned changing the variable or function should be done by returning the entire function, like this:
const goToNext = () => {
return setQuestionIndex( (prevQuestionIndex) => prevQuestionIndex + 1);
}