Browse Source

Warn against side effects in useMemo (#1576)

main
Dan Abramov 6 years ago
committed by GitHub
parent
commit
a946fb3783
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      content/docs/hooks-faq.md
  2. 2
      content/docs/hooks-reference.md

2
content/docs/hooks-faq.md

@ -343,6 +343,8 @@ const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
This code calls `computeExpensiveValue(a, b)`. But if the inputs `[a, b]` haven't changed since the last value, `useMemo` skips calling it a second time and simply reuses the last value it returned.
Remember that the function passed to `useMemo` runs during rendering. Don't do anything there that you wouldn't normally do while rendering. For example, side effects belong in `useEffect`, not `useMemo`.
**You may rely on `useMemo` as a performance optimization, not as a semantic guarantee.** In the future, React may choose to "forget" some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without `useMemo` — and then add it to optimize performance. (For rare cases when a value must *never* be recomputed, you can [lazily initialize](#how-to-create-expensive-objects-lazily) a ref.)
Conveniently, `useMemo` also lets you skip an expensive re-render of a child:

2
content/docs/hooks-reference.md

@ -288,6 +288,8 @@ Returns a [memoized](https://en.wikipedia.org/wiki/Memoization) value.
Pass a "create" function and an array of inputs. `useMemo` will only recompute the memoized value when one of the inputs has changed. This optimization helps to avoid expensive calculations on every render.
Remember that the function passed to `useMemo` runs during rendering. Don't do anything there that you wouldn't normally do while rendering. For example, side effects belong in `useEffect`, not `useMemo`.
If no array is provided, a new value will be computed whenever a new function instance is passed as the first argument. (With an inline function, on every render.)
**You may rely on `useMemo` as a performance optimization, not as a semantic guarantee.** In the future, React may choose to "forget" some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without `useMemo` — and then add it to optimize performance.

Loading…
Cancel
Save