Fix: preserve optional chaining when inner fn in hook callback is con…#36119
Fix: preserve optional chaining when inner fn in hook callback is con…#36119arsyadal wants to merge 1 commit intofacebook:mainfrom
Conversation
…ditionally called
|
Hi @arsyadal! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
Summary:
Fixes #36057
The React Compiler was incorrectly removing optional chaining (
?.) byassuming a variable is always non-null, based on a non-optional property
access inside a conditionally-called inner function within a hook callback.
Root Cause
In
CollectHoistablePropertyLoads.ts, when analyzing a hook callback(e.g.
useEffect), the compiler recursively collects non-null assumptionsfrom inner functions (e.g.
log) that are inassumedInvokedFns. Thiscaused non-null assumptions from
logto propagate to the hook callback'sentry block — even though
logis only called conditionally(
if (currentDevice) log()).These assumptions then propagated to the component's render scope, causing
optional chains like
currentDevice?.typeto be incorrectly rewritten ascurrentDevice.type, resulting in aTypeErrorat runtime whencurrentDeviceisundefined.Fix
In
collectNonNullsInBlocks, skip recursive propagation from innerFunctionExpressionnodes when already inside a nested function context(
nestedFnImmutableContext !== null). This prevents non-null assumptionsfrom depth-2+ inner functions from leaking into the outer render scope.
Functions defined directly in the component scope (depth 0) are unaffected.