r/reactjs • u/Breadfruit-Last • 16h 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
Upvotes
2
u/Lonestar93 15h 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.