const mylist = [1,2,3,4,5];
useEffect(() => {
console.log(mylist)
}, [mylist])
This is part of my code. useEffect
doesn't trigger when I append a new element to mylist, but it does when I delete an element.
How do I fix it so that it triggers when I append new elements to mylist
I have a button doing onClick(e => mylist.push(e))
and another one onClick(e => mylist.remove(e))
const mylist = [1,2,3,4,5];
useEffect(() => {
console.log(mylist)
}, [mylist])
This is part of my code. useEffect
doesn't trigger when I append a new element to mylist, but it does when I delete an element.
How do I fix it so that it triggers when I append new elements to mylist
I have a button doing onClick(e => mylist.push(e))
and another one onClick(e => mylist.remove(e))
- 2 Show how you are appending and deleting to give some context – Brian Thompson Commented Jan 3, 2020 at 20:16
5 Answers
Reset to default 4The array that you're creating isn't being stored in state, so every render a new array is being created. The solution is to use react state:
function MyComponent() {
const [myList, setMyList] = useState([0,1,2,3,4])
useEffect(() => {
console.log(myList)
}, [myList])
return (
<div>
{JSON.stringify(myList)}
<button onClick={() => setMyList([...myList, myList.length])}>Add</button>
</div>);
}
I couldn't make a ment on @Gerard's answer until I have more reputation points. I want to add that make sure you pass an arrow function to setMyList as shown:
function MyComponent() {
const [myList, setMyList] = useState([0,1,2,3,4])
useEffect(() => {
console.log(myList)
}, [myList])
return (
<div>
{JSON.stringify(myList)}
<button onClick={() => setMyList(prevList => [...prevList, prevList.length])}>Add</button>
</div>);
}
It worked when I change the dependency to mylist.toString()
I thought useEffect does deep parison on the second parameter
You could check the length
of the array
so if the array
size changes the effect will be excecuted:
useEffect(() => {
//Your effect
}, [mylist.length])
useEffect using strict parison, but an array always es up as false, so [1] === [1] is false and [1] === [1, 2] is still false.
It likely only runs on first render, that is why it's not updating it when you add or remove from list. Try putting the length of the array as a dependancy and it'll work as you intend it to.
So,
useEffect(() => {
//stuff on myList
}, [myList.length])
So if you add something to it, it'll be paring integer to integer