-
Notifications
You must be signed in to change notification settings - Fork 50.8k
Description
What kind of issue is this?
- React Compiler core (the JS output is incorrect, or your app works incorrectly after optimization)
- babel-plugin-react-compiler (build issue installing or using the Babel plugin)
- eslint-plugin-react-hooks (build issue installing or using the eslint plugin)
- react-compiler-healthcheck (build issue installing or using the healthcheck script)
Link to repro
Repro steps
The React Compiler incorrectly removes optional chaining (?.) and replaces it with direct property access. This appears to be caused by an unsafe assumption that currentDevice is always defined, based on its usage inside a useEffect.
Original Code
import { useState, useEffect } from "react"
export default function Scanner() {
const [devices, setDevices] = useState([])
const [currentDeviceIndex, setCurrentDeviceIndex] = useState(0)
const currentDevice = devices[currentDeviceIndex]
useEffect(() => {
async function log() {
console.log(currentDevice.os)
}
if (currentDevice) log()
}, [currentDevice])
return (
<div>
device type:{" "}
{currentDevice?.type ||
(currentDevice?.os?.match(/android|ios/i) ? "mobile" : "desktop")}
</div>
)
}Compiled Output (Problematic)
if ($[4] !== currentDevice.os || $[5] !== currentDevice.type) {Issue
The compiler transforms safe optional chaining:
currentDevice?.os
currentDevice?.typeinto unsafe direct access:
currentDevice.os
currentDevice.typeRoot Cause (Incorrect Assumption)
The compiler appears to infer that currentDevice is always defined because of this code:
useEffect(() => {
async function log() {
console.log(currentDevice.os)
}
if (currentDevice) log()
}, [currentDevice])However, this assumption is incorrect because:
currentDevice.osis accessed inside a function (log)- That function is only invoked conditionally when
currentDeviceis truthy - There is no guarantee that
currentDeviceis defined outside that guarded call
Why this is a bug
When currentDevice is undefined (which is valid in this component, since devices is initially an empty array):
const currentDevice = devices[currentDeviceIndex] // undefinedthe compiled code throws:
TypeError: Cannot read properties of undefined (reading 'os')
Expected Behavior
The compiler should preserve null safety by:
- Keeping optional chaining, or
- Adding appropriate guards before property access
Example of safe output:
if ($[4] !== currentDevice?.os || $[5] !== currentDevice?.type) {Impact
- Introduces runtime crashes in otherwise safe React code
- Breaks correctness of compiled output
How often does this bug happen?
Every time
What version of React are you using?
19.2.0
What version of React Compiler are you using?
1.0.0