Home > OS >  How does useMemo() create an id for its factories?
How does useMemo() create an id for its factories?

Time:05-26

There is a function in React called useMemo()

const eg = React.useMemo(() => true, []);

If I included the same function twice, how would it know which memoization to return?

const eg1 = React.useMemo(() => Math.random(), []);
const eg2 = React.useMemo(() => Math.random(), []);

There's no explicit ID for either of these arrow functions, and -- that I know of -- there is no way to ID them except to perhaps hash their inner text. In this case, they'd both have the same ID.

What kind of funky magic is going on here?

CodePudding user response:

React knows which is which because it makes the assumption that you will always call useMemo exactly the same number of times, in exactly the same order. Thus, it knows that the 1st time you call useMemo during a render, it should check the dependency array from the 1st call last time, and return the 1st value. Then the second time you call useMemo, it checks the 2nd dependency array and returns the 2nd value. Etc.

That's why the rules of hooks insist that you can't call hooks conditionally.

CodePudding user response:

From what I understand of useMemo, it just won't be able to memorize and will always recalculate the values due to lack of parameters.

useMemo avoids calculations if function parameters are the same, if there are no parameters, a new value will be calculated on each rendering.

  • Related