简体   繁体   中英

React, ESLint: eslint-plugin-react-hooks dependency on a function in an object

I'm not sure this is a bug, but I need an explanation then. Consider the following code:

const someCallback = useCallback(() => console.log(someObj.someChildObject), [someObj.someChildObject])

ESLint rule does not give any warning about missing or wrong dependencies, however, the following code gives a warning about missing someObj dependency:

const someCallback = useCallback(() => someObj.someChildFunction(), [someObj.someChildFunction])

Can someone explain, why does the second example produce a warning? Or is it actually a bug? Using 4.0.8 version of eslint-plugin-react-hooks package

Can someone explain, why does the second example produce a warning?

Though the function might be the same the result it produces might depend on the calling context ie someObj .

Consider the following example for simplicity.

// assume someObj is just a number and someChildFunction is toString
someObj = Math.random();

// you can't memoize based on the function itself because it uses context
const someCallback = useCallback(() => someObj.toString(), [someObj.toString])

toString is the same for every number 5..toString === 4..toString but the result it produces depends on the number.

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