Skip to content

Conversation

@pritjasani08
Copy link

Summary

Fixes #35355

The React Compiler was not properly memoizing values when a const declaration appeared between React hooks. This fix ensures that const declarations don't break the memoization analysis chain.

Problem

When a const declaration appears between React hooks, the compiler's memoization logic was incorrectly pruning all active scopes, causing useMemo and other memoized values to not be properly optimized.

**Example of the bug:**pt
function Component() {
const [state, setState] = useState(0);
const someConst = 42; // ← This const between hooks breaks memoization
const memoized = useMemo(() => someConst * 2, [someConst]);
return

{memoized}
;
}## Solution
Updated the memoization logic in FlattenScopesWithHooksOrUseHIR.ts to only prune scopes whose body blocks actually contain hooks, rather than pruning all active scopes when a hook is encountered. This allows scopes created between hooks (like const declarations) to be properly memoized.

Changes

  • Modified FlattenScopesWithHooksOrUseHIR.ts to identify blocks containing hooks in a first pass
  • Updated pruning logic to only prune scopes that contain hooks, not all active scopes
  • Scopes created between hooks are now properly tracked and memoized

Test Plan

Fixes facebook#35061

The React Compiler was not properly memoizing values when a const
declaration appeared between React hooks. This fix ensures that const
declarations don't break the memoization analysis chain.

Changes:
- Updated memoization logic to only prune scopes that contain hooks
- Scopes created between hooks (like const declarations) are now properly memoized
- All existing tests pass
@meta-cla meta-cla bot added the CLA Signed label Dec 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Compiler Bug]:Compiler doesn't memoize if const is between hooks

1 participant