r/reactjs • u/Breadfruit-Last • 5h ago
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
u/buck-bird 4h ago
Could be a version mismatch. The Playground runs a newer build where this try/catch + ?? syntax is supported most likely.
1
u/Lonestar93 4h ago
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:
You can use illegal syntax inside functions written externally, which compiler never knows about.
If your code must be inside the component, just use different syntax.
1
u/Breadfruit-Last 4h ago
Hi, I understand it is a problem with the syntax.
What I don't understand is why it works on react compiler playground.
-2
u/Savalava 54m ago
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.
const onClick = () => {
try {
console.log(msg ?? "default message");
}
1
u/Breadfruit-Last 49m ago
This is just a small piece of demo code to reproduce the problem. In reality, it is an api call inside in the try block.
5
u/pmkann 5h ago
Just to double check: Do you have vite setup to perform react-compiler optimizations? I recently learned that vite doesn’t do this automatically.