The compiler incorrectly hoists closure-scoped variables, breaking lexical scoping.
The React Compiler incorrectly hoists closure-scoped variables to the top level, causing runtime errors due to broken lexical scoping. The fix requires understanding compiler optimizations and ensuring proper variable binding. The issue is reproducible but requires deep knowledge of the compiler's transformation logic.
The React Compiler incorrectly hoists closure-scoped variables to the top level when it detects they’re only used inside a closure.
This optimization breaks lexical scoping and leads to runtime errors because the moved variable is no longer properly bound.
Original Code
export function createSomething() {
const store = new SomeStore();
const Cmp = () => {
const observedStore = useLocalObservable(() => store);
return <div>{observedStore.test}</div>;
};
return Cmp;
}
Compiler Output
import { c as _c } from "react/compiler-runtime";
export function createSomething() {
const store = new SomeStore();
const Cmp = () => {
const $ = _c(2);
const observedStore = useLocalObservable(_temp);
let t0;
if ($[0] !== observedStore.test) {
t0 = <div>{observedStore.test}</div>;
$[0] = observedStore.test;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
};
return Cmp;
}
function _temp() {
return store;
}
Every time
19
Claim this issue to let others know you're working on it. You'll earn 20 points when you complete it!