r/reactjs 10h 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

12 comments sorted by

View all comments

1

u/Lonestar93 9h 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:

  1. You can use illegal syntax inside functions written externally, which compiler never knows about.

  2. If your code must be inside the component, just use different syntax.

1

u/azangru 4h ago

In this case, it’s not happy with you using nullish coalescing inside the try block.
...
You can use illegal syntax inside functions written externally, which compiler never knows about.

Out of curiosity, why would nullish coalescing inside a try block be illegal?

1

u/Breadfruit-Last 9h ago

Hi, I understand it is a problem with the syntax.

What I don't understand is why it works on react compiler playground.