Browse Source

[Beta] Tweak loop guidance

main
Dan Abramov 3 years ago
parent
commit
8a9efff83d
  1. 24
      beta/src/content/apis/react/useCallback.md
  2. 19
      beta/src/content/apis/react/useMemo.md

24
beta/src/content/apis/react/useCallback.md

@ -856,7 +856,7 @@ When you find which dependency is breaking memoization, either find a way to rem
### I need to call `useCallback` for each list item in a loop, but it's not allowed {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/}
You can't call `useCallback` in a loop:
Suppose the `Chart` component is wrapped in [`memo`](/api/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useCallback` in a loop:
```js {5-14}
function ReportList({ items }) {
@ -879,7 +879,7 @@ function ReportList({ items }) {
}
```
Instead, extract a component for each item and memoize data for individual items:
Instead, extract a component for an individual item, and put `useCallback` there:
```js {5,12-21}
function ReportList({ items }) {
@ -905,3 +905,23 @@ function Report({ item }) {
);
}
```
Alternatively, you could remove `useCallback` in the last snippet and instead wrap `Report` itself in [`memo`.](/api/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```js {5,6-8,15}
function ReportList({ items }) {
// ...
}
const Report = memo(function Report({ item }) {
function handleClick() {
sendReport(item)
}
return (
<figure>
<Chart data={data} />
</figure>
);
});
```

19
beta/src/content/apis/react/useMemo.md

@ -1274,7 +1274,7 @@ When you find which dependency is breaking memoization, either find a way to rem
### I need to call `useMemo` for each list item in a loop, but it's not allowed {/*i-need-to-call-usememo-for-each-list-item-in-a-loop-but-its-not-allowed*/}
You can't call `useMemo` in a loop:
Suppose the `Chart` component is wrapped in [`memo`](/api/react/memo). You want to skip re-rendering every `Chart` in the list when the `ReportList` component re-renders. However, you can't call `useMemo` in a loop:
```js {5-11}
function ReportList({ items }) {
@ -1317,3 +1317,20 @@ function Report({ item }) {
);
}
```
Alternatively, you could remove `useMemo` and instead wrap `Report` itself in [`memo`.](/api/react/memo) If the `item` prop does not change, `Report` will skip re-rendering, so `Chart` will skip re-rendering too:
```js {5,6,12}
function ReportList({ items }) {
// ...
}
const Report = memo(function Report({ item }) {
const data = calculateReport(item);
return (
<figure>
<Chart data={data} />
</figure>
);
});
```
Loading…
Cancel
Save