When you need to add a large object to a react hooks (useEffect
, useMemo
, useCallback
) dependency array, what's the best practice when doing so.
let largeDeepObject = {
parent: {
child: { ... },
},
};
useEffect(() => {
// do something
}, [largeDeepObject]);
const memoizedValue = useMemo(() => {
// do something
}, [largeDeepObject]);
React uses Object.is()
for array dependency comparison which will return false
on objects without a reference to the original value. This will re-render the hook even when the object hasn't changed.
const foo = { a: 1 };
const bar = { a: 1 };
const sameFoo = foo;
Object.is(foo, foo); // true
Object.is(foo, bar); // false
Object.is(foo, sameFoo); // true
CodePudding user response:
It would be best to reference strictly the values that you actually use in the effect, as granular as possible. Many times these will be primitives which means that you don't even have to worry about them unnecessarily changing.
If you do have to reference objects or other structures such as arrays then you need to make sure their reference stays the same. You should always be aware why your references change and prevent this when not necessary. Besides helping your effects work seamlessly it will most probably also positively impact your app performance.
Don't forget to extract your variables outside the component whenever possible (i.e. when not using props
or state
). This way you will not need to add them as dependencies.
Also, using memoization up the components chain is always an option (useMemo
, useCallback
and soon useEvent
), just don't overuse it unnecessarily! :)