reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
10.95k stars 7.47k forks source link

useMemo - must the create function be a pure function? #3348

Open AjaxSolutions opened 3 years ago

AjaxSolutions commented 3 years ago

The doc is not clear if the useMemo "create" function must be a pure function. A pure function must depend on its inputs to generate output.

Can the "create" function read the content of a ref? This would make it impure, but can such a function be used in the useMemo hook?

gaearon commented 3 years ago

Yes it should be pure. We should clarify this.

AjaxSolutions commented 3 years ago

Yes it should be pure. We should clarify this.

Could you please clarify what is meant by "pure" in this case?

Does pure mean that all these requirements must be fulfilled as listed in this description or does it mean that the function should only have no side effects?

See the official React useMemo documentation example.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

The function computeExpensiveValue value may or may not be pure; however, this is not the function passed to useMemo. The function passed to useMemo is the anonymous arrow function, and this function is not pure because it reads data a and b from the environment.