Skip to content
Advertisement

react useEffect comparing objects

I am using react useEffect hooks and checking if an object has changed and only then run the hook again.

My code looks like this.

JavaScript

Unfortunately it keeps running as the objects are not being recognised as being the same.

I believe the following is an example of why.

JavaScript

Perhaps running JSON.stringify(apiOptions) works?

Advertisement

Answer

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:

JavaScript

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

Example #1

JavaScript

Alternatively

You could write a deep comparable useEffect as described here:

JavaScript

You can use it like you’d use useEffect.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement