react
react copied to clipboard
Bug: Inefficiency when hooks return multiple values
React compiler inefficiently re-evaluates code when dependencies that do not affect the result have changed. Specifically, when the hook returns multiple values.
Input code:
export default function Test() {
const [data, refetch] = useData();
const y = deepClone(data);
return (
<div>
<button onClick={refetch}>
Refetch
</button>
<span>
{JSON.stringify(y)}
</span>
</div>
);
}
Check the output JS here - Link to Playground
Steps To Reproduce
- Use the provided original code in a React component.
- Observe the generated code by the React compiler.
- Note that
deepClone(data)
is re-evaluated when refetch changes.
Check the playground link above ^
The current behavior
- The line const
y = deepClone(data);
is re-evaluated whenever refetch changes, even if data remains the same. - This inefficiency arises because the compiler does not memoize
y
independently from other variables liket1
.
The expected behavior
y
should be memoized separately to avoid re-computation when only refetch changes and data remains the same.