sajad torkamani

The useEffect hook is a source of many bugs. Follow these tips to minimize bugs.

1. Always specify a dependency array

If you omit the dependency array, the effect will run after every re-render. You rarely want this.

2. Make sure every item in the dependency array is a primitive type.

React uses the Object.is() function to compare the value of each item in the dependency array to the value it had in the previous render.

If you use non-primitive types like objects, arrays or functions, Object.is() will return false if the references aren’t the same:

const obj1 = { name: 'John' }
const obj2 = { name: 'John' }

// Returns false because obj1 and obj2 are two different references
Object.is(obj1, obj2) // false

// Returns false because obj1 and obj2 are two different references
Object.is({ name: 'John' }, { name: 'John'}) // false

Object.is(obj1, obj1) // true

Using non-primitives is problematic because it’s easy for references to objects or arrays to change between re-renders. If you must use objects or arrays, you can memoize them.