we often used variable of array type with useState
hook in react and came in a dead end where our variable doesn't update as wanted.
so here are some ways-
Consider
const fruits = ["apple", "orange", "grapes", "strawberry"]
const [fruitsState, setFruits] = useState(fruits)
Read
To read data in variable u can simply write
<>
{/* console.log(fruits) */}
<ul>
{fruitsState.map((fruit)=>{
return <li>{fruit}</li>
})
}
</ul>
<>
Update
To update elements in array
setFruits(setFruitsState.filter((fruit)=> `Lovely, ${fruit}`))
Add
setFruits([newFruit, ...fruitsState])
Delete
To delete elements from array
// select a fruit
const deleteFruit = 'apple'
setFruits(fruitsState.filter(fruit => fruit!=deleteFruit))
Enjoy Hacking
CRA (create react app). ๐
Read more articles about react and its libraries.
That's it for this article, hope you get something useful. Share your thoughts on this article in socials.
Let's Connect -
Tweet Thanks
https://linktr.ee/kunal.dev
Top comments (3)
I think there's a mistake in your add example, you need to spread the current state, not the new item:
Thanks ๐
I would say that using useReducer is much better than useState to manage an array