Instead of passing the entire object to the dependency array, make sure that you only pass name. Which you can do by returning the names

const [objects, setObjects] = useState([])

useEffect(()=> {
      getAllObjects()
}, [getAllObjects, ...objects.map(item => item.name)])
Answer from Shubham Khatri on Stack Overflow
🌐
DEV Community
dev.to › aileenr › til-you-can-watch-for-nested-properties-changing-in-react-s-useeffect-hook-26nj
TIL: You can watch for nested properties changing in React's useEffect() hook - DEV Community
January 18, 2022 - But what about if you have nested data, say an object containing form data, e.g. const values = { name: 'Aileen', age: 26, city: 'Edinburgh', favoriteFood: 'pizza 🍕' } What if I want to trigger a side-effect when the user updates just their age, and not when any other value changes? It seems obvious in hindsight, but you can watch for nested values changing simply by referencing the nested property with dot notation: useEffect(()=> { ageChangeSideEffect(values.age); }, [values.age])
Discussions

useEffect() doesn't trigger on property object change (Deep object)
I have a component which takes a deep object as argument. I want to be able to dynamically alter my component based on the property that I pass - But for some reason my useEffect() loop doesn't run... More on stackoverflow.com
🌐 stackoverflow.com
What if you need to check an object in the useEffect dependency array?
Passing stateful objects to the useEffect is fine? If it’s coming from redux the only time the reference would change is dispatching an action that would change them. The only problem with passing non primitives to useEffects is when you create them during the render, making the reference unstable More on reddit.com
🌐 r/reactjs
11
2
August 2, 2023
reactjs - useEffect React Hook: detecting the change of a property for each object in an array - Stack Overflow
StackOverflow, I'm having a question about React Hooks, more particularly, useEffect hook. I'm aware that one use case of useEffect hook is to capture changes of certain state variables. Let's supp... More on stackoverflow.com
🌐 stackoverflow.com
June 8, 2021
react useEffect comparing objects - javascript
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am using react useEffect hooks and checking if an object has changed ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 74755341 › useeffect-not-re-rendering-on-use-state-object-property-change
reactjs - UseEffect not re-rendering on use state object property change - Stack Overflow
December 10, 2022 - Like that is the reason why useState returns setXXX function as second item in the array, which you ignore currently. After the category is updated completely (reference to this object is changed) - this useEffect will wake up and compare categoryId of this object.
🌐
Stack Overflow
stackoverflow.com › questions › 69067301 › useeffect-doesnt-trigger-on-property-object-change-deep-object
useEffect() doesn't trigger on property object change (Deep object)
The easy solution would be to remove the dependency array - But that just makes the useEffect loop run infinitely ... You don't show how you're passing in sourceArray, particularly at the point where it updates - but you strongly imply you're mutating it. So the obvious solution is to not do that in the parent component, but pass in a new object reference instead. ... Can you provide a snippet of how the data structure for groups look like. ... Make a copy of the array when updating in state so that the object reference changes.
🌐
Marcoghiani
marcoghiani.com › blog › how-to-use-the-react-hook-usedeepeffect
UseDeepEffect Hook in React: A Guide to Better Performance
February 17, 2020 - We can write some basic code to ... useEffect Hook doesn’t perform a shallow comparison on objects, but it checks whether its reference changes or not....
🌐
Reddit
reddit.com › r/reactjs › what if you need to check an object in the useeffect dependency array?
r/reactjs on Reddit: What if you need to check an object in the useEffect dependency array?
August 2, 2023 -

I have an object that looks something like this stored in a Redux store:

[ layer1: false, layer2: true, layer3: false]

These flags represent layers that are shown or hidden on a Leaflet map.

The various fields are toggled by their associated inputs and in the component which consumes them, I need to add or remove the specified layers when the object above changes.

Since you can't pass non-primitives into the useEffect dependency array, I considered trying the following I found on SO:

useEffect(() => {

// ...

), [JSON.stringify(myLayersObject)])

This doesn't work, I think because it's effectively passing a constant in the dependency list.

I am also considering using a byte to store the flags and doing bitwise manipulation to check the values. That should work, but it may be somewhat unclear to other devs what I am doing, so any alternative suggestions are welcome.

The usual remedy of trying to extract only the primitive property you care about doesn't work, because i need to care about all of them. In the real code there are only layers, and I suppose I could make 6 useEffect hooks with dependency arrays like [myLayersObject.layer1], etc. but that is also ugly.

Any suggestions?

Thanks.

🌐
Medium
medium.com › @humbleCoder007 › adding-nested-properties-as-dependencies-to-useeffect-hook-c6a10ca6d6b1
Adding Nested Properties As Dependencies To useEffect Hook | by The Humble Coder | Medium
March 1, 2023 - I just want to point out, that they key thing is NOT that we use destructuring but that we pass specific properties instead of the entire object as a dependency. We could also write this code and it would work in the same way. useEffect(() => { // code that only uses someProperty ... }, [someObject.someProperty]); This works just fine as well! But you should avoid this code: useEffect(() => { // code that only uses someProperty ... }, [someObject]); Why? Because now the effect function would re-run whenever ANY property of someObject changes - not just the one property (someProperty in the above example) our effect might depend on.
Find elsewhere
🌐
Significa
significa.co › blog › dangers-of-using-objects-in-usestate-useeffect-reactjs-hooks
The dangers of using objects in ReactJS useState and useEffect hooks.
February 2, 2023 - In other words, the hook compares (===) the "old" and "new" states and concludes that the object hasn't changed and won't trigger a re-render, causing the object count label to stay the same. The Functioning increase of the object count button fixes the issue by creating and passing a shallow copy of the objectCount to the setter function. It basically keeps the same object properties but creates a new object reference so that the hook strict equality comparison determines that the state changes, and immediately triggers a re-render.
Top answer
1 of 7
115

Use apiOptions as state value

I'm not sure how you are consuming the custom hook but making apiOptions a state value by using useState should work just fine. This way you can serve it to your custom hook as a state value like so:

const [apiOptions, setApiOptions] = useState({ a: 1 })
const { data } = useExample(apiOptions)

This way it's going to change only when you use setApiOptions.

Example #1

import { useState, useEffect } from 'react';

const useExample = (apiOptions) => {
  const [data, updateData] = useState([]);
  
  useEffect(() => {
    console.log('effect triggered')
  }, [apiOptions]);

  return {
    data
  };
}
export default function App() {
  const [apiOptions, setApiOptions] = useState({ a: 1 })
  const { data } = useExample(apiOptions);
  const [somethingElse, setSomethingElse] = useState('default state')

  return <div>
    <button onClick={() => { setApiOptions({ a: 1 }) }}>change apiOptions</button>
    <button onClick={() => { setSomethingElse('state') }}>
      change something else to force rerender
    </button>
  </div>;
}

Alternatively

You could write a deep comparable useEffect as described here:

function deepCompareEquals(a, b){
  // TODO: implement deep comparison here
  // something like lodash
  // return _.isEqual(a, b);
}

function useDeepCompareMemoize(value) {
  const ref = useRef() 
  // it can be done by using useMemo as well
  // but useRef is rather cleaner and easier

  if (!deepCompareEquals(value, ref.current)) {
    ref.current = value
  }

  return ref.current
}

function useDeepCompareEffect(callback, dependencies) {
  useEffect(
    callback,
    dependencies.map(useDeepCompareMemoize)
  )
}

You can use it like you'd use useEffect.

2 of 7
30

If the input is shallow enough that you think deep equality would still be fast, consider using JSON.stringify:

const useExample = (apiOptions) => {
    const [data, updateData] = useState([]);
    const apiOptionsJsonString = JSON.stringify(apiOptions);

    useEffect(() => {
       const apiOptionsObject = JSON.parse(apiOptionsJsonString);
       doSomethingCool(apiOptionsObject).then(response => {               
           updateData(response.data);
       })
    }, [apiOptionsJsonString]);

    return {
        data
    };
};

Note it won’t compare functions.

🌐
DevPress
devpress.csdn.net › react › 62fe3c96c677032930804869.html
Having Objects as dependencies in React useEffect hook_rAc-React
August 18, 2022 - Due to the above change , It is ... change i.e count’s value keeps being 0. As expected , the function passed to useEffect hook doesn’t run 👍🏿 · However , there’s a gotcha in this useEffect hook when the count value in the dependencies array is an object . Let’s say , the count’s value is stored as a property in an object ...
🌐
Untitled Publication
haybeecodes.hashnode.dev › having-objects-as-dependencies-in-react-useeffect-hook
Having objects as dependencies in React useEffect hook
August 17, 2022 - Due to the above change , It is ... change i.e count’s value keeps being 0. As expected , the function passed to useEffect hook doesn’t run 👍🏿 · However , there’s a gotcha in this useEffect hook when the count value in the dependencies array is an object . Let’s say , the count’s value is stored as a property in an object ...
🌐
Today I Learned
til.hashrocket.com › posts › z1xzaupgpd-run-side-effect-when-a-prop-changes-whooks
Run side effect when a prop changes w/Hooks - Today I Learned
May 25, 2022 - useEffect(() => console.log('value changed!'), [props.isOpen]); Now, you will see "value changed!" both on the first render and everytime isOpen changes.
🌐
Ben Ilegbodu
benmvp.com › blog › object-array-dependencies-react-useEffect-hook
Object & array dependencies in the React useEffect Hook | Ben Ilegbodu
January 2, 2021 - Now that the team object is created within useEffect, it'll only be created when the effect is run. And now that id, name, and active are specified as dependencies (which are primitive values), the effect will only run when their values change.
🌐
Stack Overflow
stackoverflow.com › questions › 78810230 › how-to-trigger-useeffect-on-change-of-a-deeply-nested-object
reactjs - How to trigger useEffect on change of a deeply nested object? - Stack Overflow
So the way-around I implemented was to take another state that will store the total number of variants and then pass selectedProducts as dependency of another useEffect which will then change the totalVariantsCount.
🌐
Profy.dev
profy.dev › article › react-useeffect-with-object-dependency
React useEffect and objects as dependency - 4 approaches to avoid unnecessary re-renders
March 19, 2024 - Technically, this isn't problematic, because the effect is run whenever one of the values of the params object changes.
🌐
Medium
medium.com › suyeonme › react-lets-deep-dive-into-deps-array-of-useeffect-13ab96468db7
React: Let’s deep dive into deps array of useEffect | by Suyeon Kang | suyeonme | Medium
July 31, 2022 - const useEffectTest = (user) => ... If we want to run useEffect based on the object(reference type), we should compare dependencies with deep equal....