DEV Community

Kunal Agrawal
Kunal Agrawal

Posted on

3 1 1 1 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay