Skip to content

Instantly share code, notes, and snippets.

@poteto
Last active June 18, 2024 13:14
Show Gist options
  • Save poteto/37c076bf112a07ba39d0e5f0645fec43 to your computer and use it in GitHub Desktop.
Save poteto/37c076bf112a07ba39d0e5f0645fec43 to your computer and use it in GitHub Desktop.
React Compiler compatibility module for codebases unable to use React 19
module.exports = function(api) {
return {
plugins: [
[
'babel-plugin-react-compiler', {
runtimeModule: 'react-compiler-runtime'
}
]
]
}
}
{
"dependencies": {
"react-compiler-runtime": "file:./lib/react-compiler-runtime"
},
"devDependencies": {
"babel-plugin-react-compiler": "latest"
}
}
// lib/react-compiler-runtime/index.js
const React = require('react');
const $empty = Symbol.for("react.memo_cache_sentinel");
/**
* DANGER: this hook is NEVER meant to be called directly!
*
* Note that this is a temporary userspace implementation of this function
* from React 19. It is not as efficient and may invalidate more frequently
* than the official API. Please upgrade to React 19 as soon as you can.
**/
export function c(size: number) {
return React.useState(() => {
const $ = new Array(size);
for (let ii = 0; ii < size; ii++) {
$[ii] = $empty;
}
// @ts-ignore
$[$empty] = true;
return $;
})[0];
}
// lib/react-compiler-runtime/package.json
{
"name": "react-compiler-runtime",
"version": "0.0.1",
"license": "MIT",
"main": "index.js",
"dependencies": {
"react": "^18.2.0"
}
}
@brandonpapworth
Copy link

brandonpapworth commented Jun 18, 2024

+1ing @jsonz1993

Middle ground may even be using useRef to keep it safely contained and consistent.

// lib/react-compiler-runtime/index.js

const { useRef } = require('react');
const $empty = Symbol.for("react.memo_cache_sentinel");
/**
 * DANGER: this hook is NEVER meant to be called directly!
 *
 * Note that this is a temporary userspace implementation of this function
 * from React 19. It is not as efficient and may invalidate more frequently
 * than the official API. Please upgrade to React 19 as soon as you can.
 **/
export function c(size: number): any[] {
  const memoArrayRef = useRef<any[] | undefined>(undefined)

  if (!memoArrayRef.value) {
    memoArrayRef.value = []
    for (let i = 0; i < size; i += 1) {
      memoArrayRef.value.push($empty)
    }
    // @ts-ignore
    memoArrayRef.value[$empty] = true;
  }

  return memoArrayRef.value
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment