If you need to register an effect on a non-primitive in React, you’ll eventually
notice that it doesn’t behave as expected.
Indeed, React uses shallow comparison
to compare variables and this may trigger effects when a object was re-created
even if its content has not changed.
This is usually the sign of performance issues and should be addressed.
However, once it a while it makes sense to use a quick work around:
a custom hook I call useDeepCompareEffect
:
import { useEffect, useRef } from 'react'
import _ from 'lodash'
export default function useDeepCompareEffect(callback, dependencies) {
const ref = useRef()
return useEffect(() => {
if (_.isEqual(dependencies, ref.current)) {
return
}
ref.current = dependencies
callback()
}, dependencies) // eslint-disable-line react-hooks/exhaustive-deps
}
This hook uses Lodash’s isEqual
to
compare the dependencies. It can be used anywhere in place of usEffect
.
⚠️ Remember, resorting to this hooks probably hides other issues with the code.