DEV Community

Kunal Agrawal
Kunal Agrawal

Posted on

JavaScript, useState React Array Handling methods.

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)
Enter fullscreen mode Exit fullscreen mode

Read

To read data in variable u can simply write

<>
    {/* console.log(fruits) */}
    <ul>
        {fruitsState.map((fruit)=>{
            return <li>{fruit}</li>
        })
    }
</ul>
<>
Enter fullscreen mode Exit fullscreen mode

Update

To update elements in array

setFruits(setFruitsState.filter((fruit)=> `Lovely, ${fruit}`))
Enter fullscreen mode Exit fullscreen mode

Add

setFruits([newFruit, ...fruitsState])
Enter fullscreen mode Exit fullscreen mode

Delete

To delete elements from array

// select a fruit
const deleteFruit = 'apple'
setFruits(fruitsState.filter(fruit => fruit!=deleteFruit))
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
brense profile image
Rense Bakker

I think there's a mistake in your add example, you need to spread the current state, not the new item:

setFruits(current => [...current, newFruit])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
itskunal profile image
Kunal Agrawal

Thanks 💖

Collapse
 
franlol profile image
franlol

I would say that using useReducer is much better than useState to manage an array