HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Push method in React Hooks (useState)?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
hooksusestatereactmethodpush

Problem

How to push element inside useState array React hook?
Is that as an old method in react state? Or something new?

E.g. setState push example ?

Solution

When you use useState, you can get an update method for the state item:

const [theArray, setTheArray] = useState(initialArray);


then, when you want to add a new element, you use that function and pass in the new array or a function that will create the new array. Normally the latter, since state updates are asynchronous and sometimes batched:

setTheArray(oldArray => [...oldArray, newElement]);


Sometimes you can get away without using that callback form, if you only update the array in handlers for certain specific user events like click (but not like mousemove):

setTheArray([...theArray, newElement]);


The events for which React ensures that rendering is flushed are the "discrete events" listed here.

Live Example (passing a callback into setTheArray):



const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [...oldArray,
Entry ${oldArray.length}]);
};
return [
,
{theArray.map(entry =>
{entry}
)}

];
}

ReactDOM.render(
,
document.getElementById("root")
);







Because the only update to theArray in there is the one in a click event (one of the "discrete" events), I could get away with a direct update in addEntry:



const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray([...theArray,
Entry ${theArray.length}]);
};
return [
,
{theArray.map(entry =>
{entry}
)}

];
}

ReactDOM.render(
,
document.getElementById("root")
);



Code Snippets

const [theArray, setTheArray] = useState(initialArray);
setTheArray(oldArray => [...oldArray, newElement]);
setTheArray([...theArray, newElement]);

Context

Stack Overflow Q#54676966, score: 815

Revisions (0)

No revisions yet.