concept expensive function in category react

appears as: The expensive functions, expensive functions, expensive function, n expensive function, expensive functions
React Hooks in Action

This is an excerpt from Manning's book React Hooks in Action.

The expensive functions run on every render

We need some way of asking React to run the expensive functions only if their output is likely to be different. For getAnagrams, that’s if the sourceText value changes. For getDistinct, that’s if the anagrams array changes.

  • Pass useMemo the expensive function you want to memoize.
  • const value = useMemo(
    () => expensiveFn(dep1, dep2),
    [dep1, dep2]
    );
  • Pass the useMemo hook a list of dependencies for the expensive function.
  • const value = useMemo(
    () => expensiveFn(dep1, dep2),
    [dep1, dep2]
    );

    If the values in the dependencies array don’t change from one call to the next, useMemo can return its stored result for the expensive function.