'React useEffect doesn't trigger when array in an object state changes [duplicate]
The scenario is that there is an object state with an array in it. I want useEffect to be executed when values are added or changed in it. I tried a few solutions but none of them worked.
const [filter, setFilter] = useState({})
const firstUpdate = useRef(true);
useEffect(() => {
console.log("Filter Updated")
if (firstUpdate.current) return firstUpdate.current = false;
// API Calls Here
}, [filter])
const handler = (categoryName, categoryId) => {
let x = filter;
x.categoryIDs = [categoryId];
setFilter(x)
}
Solution 1:[1]
React compares by reference. You simply modify a property of an object and use that in the new state, this wont work.
Try setFilter({...x}).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Istvan Tabanyi |
