FAQ: The State Hook - Arrays in State

In this exercise, we are dealing with function components. If you look in the file GroceryCart.js, we have declared and initialized state with the statement:
const [cart, setCart] = useState([]);
The [] within the parentheses tells us that cart is going to be an array, initially an empty array. (If we had initialized it using somether other than [], such as a string or an object {}, then that would clue us in as to how we mean to store our data in our cart). We can use setCart to change the value of cart.

Coming back to the snippet you posted, the addItem function will be taking in an item which is going to be a string. If we did something like setCart([item]);, we will set the value of cart to be an array consisting of just this item. The problem is that doing so would overwrite our previous array. Initially we have an empty array, so overwriting that array with a new array i.e. [item] is fine. But, if our cart wasn’t empty but was something like ["Carrots", "Kale"], then something like setCart(["Lemons"]); would mean the old array would be lost and replaced by just ["Lemons"]. Obviously, we don’t want this and we want the item to be added to our existing cart. We want our cart to be ["Lemons", "Carrots", "Kale"].

If we don’t care about overwriting the old value, then setCart([item]); works fine.
But, if we want to preserve the existing old value or want to use the old value in some calculation, then the state setter function allows us this flexibility. All we need to do is just pick a parameter name and the state setter will automatically pass the previous value as the argument.
In our case, we have picked prev as the parameter name. There is nothing special about the name prev. We could have picked a different name, but prev is a good choice as it reminds us of the word previous. So our basic structure is setCart((prev) => { \\do stuff here with prev });
When we call our state setter with some item, the existing value of cart e.g. ["Carrots", "Kale"] will automatically be assigned to our parameter prev. Within the function body of our arrow function, we can use prev as we want. In this particular snippet, we create a new array whose first element is our new item and the ...prev spread syntax means that we expand the elements from our previous array. So, if item is "Lemons" and prev is ["Carrots", "Kale"] , then [item, ..prev] will be ["Lemons", "Carrots", "Kale"]. We then return this array so that the value of cart is updated to this new array.

18 Likes