xxxxxxxxxx
const [state, setState] = useState([]);
//push new array
setState(prevState => [prevState, array]);
//push new item
setState(prevState => [prevState, item]);
//returning other state val beside stateItem1
setState(prevState => {
return{
prevState,
stateItem1 : stateVal1
}
})
//using class function
this.setState({
data: [this.state.data, array],
})
xxxxxxxxxx
const [array,setArray] = useState([]);
Push value at the end:
setArray(oldArray => [oldArray,newValue] );
Push value at the start:
setArray(oldArray => [newValue,oldArray] );
xxxxxxxxxx
const {useState, useCallback} = React;
function Example() {
const [theArray, setTheArray] = useState([]);
const addEntryClick = () => {
setTheArray(oldArray => [oldArray, `Entry ${oldArray.length}`]);
};
return [
<input type="button" onClick={addEntryClick} value="Add" />,
<div>{theArray.map(entry =>
<div>{entry}</div>
)}
</div>
];
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);