Search code examples
reactjseslinteslint-plugin-react-hooks

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


Solution

  • 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 i.e. 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.