r/reactjs • u/Breadfruit-Last • Aug 13 '26
Needs Help React compiler question
Hi, I am trying to use react compiler on a component like this
export function Test({ msg }: { msg?: string }) {
"use memo";
const onClick = () => {
try {
console.log(msg ?? "default message");
} catch (error) { }
};
return (
<button onClick={onClick}>
<span>SAVE</span>
</button>
);
}This works on react compiler playground but not locally when I compile it with Vite, it doesn't work due to an error "Support value blocks (conditional, logical, optional chaining, etc) within a try/catch statement".
Why does the compiler behave differently on playground and vite?
Thanks
3
Upvotes
7
u/pmkann Aug 13 '26
Just to double check: Do you have vite setup to perform react-compiler optimizations? I recently learned that vite doesn’t do this automatically.
3
u/Lonestar93 Aug 13 '26
React Compiler bails out when you use syntax it can’t rewrite. Unfortunately this also applies to the function bodies of event handlers and effects, which it never rewrites anyway.
In this case, it’s not happy with you using nullish coalescing inside the try block.
Two ways:
6
u/buck-bird Aug 13 '26
Could be a version mismatch. The Playground runs a newer build where this try/catch + ?? syntax is supported most likely.
3
u/Working_Quote_3029 Aug 13 '26
Hi — the playground isn't running your version, and that's the whole difference.
The playground builds the compiler from React's main branch. On npm, the
latesttag forbabel-plugin-react-compileris 1.0.0, while experimental builds ship nightly (most recent right now:0.0.0-experimental-a1856f3-20260507). So a bailout that was fixed after 1.0.0 compiles fine in the playground and still throws in your Vite build.Check what you actually have:
Then close the gap:
If it compiles after that, it's purely a version gap and your Vite config was never the problem. If it still throws, the try/catch bailout is still open upstream (facebook/react#35570) and the reliable workaround is moving the try block into a function defined outside the component — the compiler doesn't rewrite those bodies anyway, so you lose nothing.
1
u/abrahamguo Aug 13 '26
Can you provide a link to your local project? It’s difficult for us to help without being able to reproduce the issue ourselves.
-3
u/Savalava Aug 13 '26
Why are you writing this code anyway? If it fails on code that makes no sense, who cares? Try / catch with console.log does not make any sense.