Set State of a list

48 Views Asked by At

When I tried to set the state of my list, I tried two methods.

setEatenFoodList(prevList => {
        prevList.unshift(addedFood);
        return prevList;
})

This method adds the addedFood two times.

setEatenFoodList([...eatenFoodList, addedFood])

When this method adds it one time, which is what I want. But, I want to know the difference between these two methods.

1

There are 1 best solutions below

1
On

As to your last question what both methods are doing are similar with unshift adding the addedFood in front of the eatenFoodList array while the in second method eatenFoodList is first destructured and then addedFood is added.

Need more context on what conditions you are updating the eatenFoodList state to find out how the first method is executing twice.