1

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)
    
  }
Brian Thompson
  • 11,484
  • 2
  • 21
  • 37

1 Answers1

-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}).

Istvan Tabanyi
  • 634
  • 3
  • 8