Update and Clear an Array in State React
In this tutorial, you will learn how to update and delete an array in state react.
Steps:
1-Define a state array
2-Update the state array
3-Clear the state array
1-Define a state array
We will create an array of fruits as the following:
const [fruits, setFruits] = useState(['banana','apple','strawberries']);
2-Update the state array
We will add orange fruit to our array as the following:
setFruits([...fruits,'orange']);
Pass our current ‘fruits’ array values as a copy using the spread operator. And we add the new element which comes after the comma, so our process is like setArray([currentArrayValues,theNewElement]), which will return an array containing our old data and the new one.
3-Clear the state array
To Clear our array, we need to write the following:
setFruits([]);
I hope this article was helpful!