简体   繁体   中英

What's the best practice for adding an Object to a React hooks (useEffect, useMemo) dependancy array?

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

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 (ie 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: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM