Posts Learn Components Snippets Categories Tags Tools About
/

How to Push Into State Array in ReactJS

Learn how to push into state array in React JS the easy way

Created on Mar 22, 2022

3161 views

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]);

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

Load comments for How to Push Into State Array in ReactJS

)