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)
}
CodePudding user response:
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})
.