[Beta] Tweak loop guidance

This commit is contained in:
Dan Abramov
2022-09-22 15:13:55 +01:00
parent 5812e54093
commit 8a9efff83d
2 changed files with 40 additions and 3 deletions

View File

@@ -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>
);
});
```

View File

@@ -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>
);
});
```