简体   繁体   中英

React Hooks: Why does the exhaustive-deps linter rule want a local function used in useMemo in the dependency list?

If I use a local function in the function I pass to useMemo (or other hooks), the exhaustive-deps linter rule wants the local function in the dependency list of useMemo . I understand that with each render, the local function is a new instance. But since it never really changes, in my opinion it's unnecessary to put in in the dependency list, particularly because then I need to use useCallback for the function (what makes the code more complicated).

Here is a working example:

const [inputNumber, setInputNumber] = useState(35);

function calculateFibonacciNumber(number) {
   return number < 1 ? 0 : number <= 2 ? 1 
      : calculateFibonacciNumber(number - 1) + calculateFibonacciNumber(number - 2);
};

const fibonacciNumber = useMemo(() => {
   return calculatedFibonacciNumber = calculateFibonacciNumber(inputNumber);
}, [inputNumber]); // Here the exhaustive-deps rule wants calculateFibonacciNumber in the dependency list

So, is there a real reason why calculateFibonacciNumber should be placed in the dependency list (via useCallback )?

I guess the reason behind that is you are using calculateFibonacciNumber outside still of useMemo .

Maybe you could try to move the definition inside, just like this:

const fibonacciNumber = useMemo(() => {
   function calculateFibonacciNumber(number) {
      return number < 1 ? 0 : number <= 2 ? 1 
         : calculateFibonacciNumber(number - 1) + calculateFibonacciNumber(number - 2);
   };

   return calculatedFibonacciNumber = calculateFibonacciNumber(inputNumber);
}, [inputNumber]);

In this case you won't see that warning message.

I hope that helps!

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