I'm trying to figure out the working of React Hook API. I'm trying to add a number to a list. The code that I commented, i.e myArray.push... doesn't seem to perform the operation, though the code below it is working fine. Why is it so?
import React, {useState} from 'react'
export default () => {
const [myArray, setArray] = useState([1,2,3])
return (
<div>
{myArray.map((item=>{
return <li>{item}</li>
}))}
<button onClick = {()=>{
// myArray.push(myArray[myArray.length-1]+1)
// setArray(myArray)
setArray([...myArray, myArray[myArray.length-1]+1])
}}>Add</button>
</div>
)
}
myArray. push(1); However, with React, we need to use the method returned from useState to update the array. We simply, use the update method (In our example it's setMyArray() ) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator.
Recap: How to add to an array in state By mastering the wrapper function, I finally solved my problem of how to add to an array in React state in three easy steps: Use useState([]) Hook to set state to [] and get state setter function. Pass wrapper function to state setter function (as a call-back function)
I would recommend using useReducer
for anything more complicated than a single value.
function App() {
const [input, setInput] = useState(0);
const [myArray, dispatch] = useReducer((myArray, { type, value }) => {
switch (type) {
case "add":
return [...myArray, value];
case "remove":
return myArray.filter((_, index) => index !== value);
default:
return myArray;
}
}, [1, 2, 3]);
return (
<div>
<input value={input} onInput={e => setInput(e.target.value)} />
<button onClick={() => dispatch({ type: "add", value: input})}>
Add
</button>
{myArray.map((item, index) => (
<div>
<h2>
{item}
<button onClick={() => dispatch({ type: "remove", value: index })}>
Remove
</button>
</h2>
</div>
))}
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With