facebook/react

Error in compiler polyfill, using React 18

kingsurf opened this issue · 1 comments

I have react 18 installed, I can see the compiler is running against my source code however during runtime this code

// Re-export React.c if present, otherwise fallback to the userspace polyfill for versions of React
// < 19.
export const c =
  // @ts-expect-error
  typeof React.__COMPILER_RUNTIME?.c === 'function'
    ? // @ts-expect-error
      React.__COMPILER_RUNTIME.c
    : function c(size: number) {
        return React.useMemo<Array<unknown>>(() => {
          const $ = new Array(size);
          for (let ii = 0; ii < size; ii++) {
            $[ii] = $empty;
          }
          // This symbol is added to tell the react devtools that this array is from
          // useMemoCache.
          // @ts-ignore
          $[$empty] = true;
          return $;
        }, []);
      };

When it reaches React.useMemo I get the error

Uncaught TypeError: Cannot read properties of null (reading 'useMemo')
    at Object.useMemo (react.development.js:1650:21)
    at c2 (index.ts:31:22)
    at AppRoutes (Routes.tsx:121:26)
    at App.tsx:14:36`

The offending code is the dispatcher being null

function useMemo(create, deps) {
  var dispatcher = resolveDispatcher();
  return dispatcher.useMemo(create, deps);
}

I am using vite with the babel-plugin-react-compiler plugin targeting React 18

react({
        babel: {
          plugins: [["babel-plugin-react-compiler", ReactCompilerConfig]],
        },
      })

Thanks for reporting. The most likely cause for this error is that the compiler accidentally compiled something that is not a component or hook, and which is getting called outside of a React render. Is it possible to share the code that got compiled and was calling into the runtime? Or create a smaller repro that you can share? Thanks!