Home / Snippets / How to Push Into State Array in ReactJS
How to Push Into State Array in ReactJS cover

How to Push Into State Array in ReactJS

3.2K

2 years ago

0 comments

To push a data into state array in ReactJS you can make use of the "useState()" hook and extract the previous data (usually using array destructure) and merge it together with the new data.

React Hooks Example

const [posts, setPosts] = useState([]);
To push value at the end of the array you can define your code like below.
setArray(oldPosts => [...oldPosts, newPost]);
To push value at the begging of the array you can just set the placement of the variable.
setArray(oldPosts => [newPost, ...oldPosts]);
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this