Search code examples
reactjsuse-effect

React useEffect detect changes in an array inside the object


I am trying to recall an API based on a state change, using useEffect hook. However, my useEffect can't detect changes made to the 'type' array. I tried using use-deep-compare-effect library, but it also couldn't detect a change.

How I can detect changes to my state?

Any help would be very much appreciated!

const [values, setValues] = useState({
        query: '',
        type: ["Tender & Auction", "Merger & Acquisition","Policy & Regulation", "Project Update", "Other"]
    })

 /// Re-run a query, after we check a filter
    useEffect(() => {
          searchAPI(values);
      }, [values]);

I am changing the values like this:

 const handleChange = (newValues) => {
        console.log(newValues)
        setValues({ ...values, type: newValues})
   };

Solution

  • This is a simple way of doing comparison without causing an infinite loop:

    useEffect(() => {
        searchAPI(values);
    }, [JSON.stringify(values)]);
    

    or if you only need to track type property:

    useEffect(() => {
        searchAPI(values);
    }, [JSON.stringify(values.type)]);