Skip to content

Commit b8e9faf

Browse files
authored
Fix handleClick compiler intro example (#7967)
* Fix handleClick compiler intro example * Use a note instead * Update src/content/learn/react-compiler/introduction.md
1 parent 85ee6b2 commit b8e9faf

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/content/learn/react-compiler/introduction.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,21 @@ const ExpensiveComponent = memo(function ExpensiveComponent({ data, onClick }) {
5050
});
5151
```
5252

53+
54+
<Note>
55+
56+
This manual memoization has a subtle bug that breaks memoization:
57+
58+
```js [[2, 1, "() => handleClick(item)"]]
59+
<Item key={item.id} onClick={() => handleClick(item)} />
60+
```
61+
62+
Even though `handleClick` is wrapped in `useCallback`, the arrow function `() => handleClick(item)` creates a new function every time the component renders. This means that `Item` will always receive a new `onClick` prop, breaking memoization.
63+
64+
React Compiler is able to optimize this correctly with or without the arrow function, ensuring that `Item` only re-renders when `props.onClick` changes.
65+
66+
</Note>
67+
5368
### After React Compiler {/*after-react-compiler*/}
5469

5570
With React Compiler, you write the same code without manual memoization:
@@ -74,7 +89,7 @@ function ExpensiveComponent({ data, onClick }) {
7489

7590
_[See this example in the React Compiler Playground](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAogB4AOCmYeAbggMIQC2Fh1OAFMEQCYBDHAIA0RQowA2eOAGsiAXwCURYAB1iROITA4iFGBERgwCPgBEhAogF4iCStVoMACoeO1MAcy6DhSgG4NDSItHT0ACwFMPkkmaTlbIi48HAQWFRsAPlUQ0PFMKRlZFLSWADo8PkC8hSDMPJgEHFhiLjzQgB4+eiyO-OADIwQTM0thcpYBClL02xz2zXz8zoBJMqJZBABPG2BU9Mq+BQKiuT2uTJyomLizkoOMk4B6PqX8pSUFfs7nnro3qEapgFCAFEA)_
7691

77-
React Compiler automatically applies the equivalent optimizations, ensuring your app only re-renders when necessary.
92+
React Compiler automatically applies the optimal memoization, ensuring your app only re-renders when necessary.
7893

7994
<DeepDive>
8095
#### What kind of memoization does React Compiler add? {/*what-kind-of-memoization-does-react-compiler-add*/}

0 commit comments

Comments
 (0)