Support useMemo w named functions

Supports useMemo invocations where the function is not an inline function, such 
as `useMemo(someFunction, [])`.
This commit is contained in:
Joe Savona
2023-04-26 18:16:28 -07:00
parent 1cccd6a815
commit afe2f5c810
3 changed files with 38 additions and 6 deletions
@@ -17,12 +17,12 @@ import {
GotoVariant,
HIR,
HIRFunction,
IdentifierId,
Identifier,
IdentifierId,
InstructionKind,
Place,
makeInstructionId,
makeType,
Place,
reversePostorderBlocks,
shrink,
} from "../HIR";
@@ -97,10 +97,8 @@ export function inlineUseMemo(fn: HIRFunction): void {
}
const body = functions.get(lambda.identifier.id);
if (body === undefined) {
CompilerError.invariant(
"Expected first argument to useMemo() to be a function expression",
lambda.loc
);
// Allow passing a named function to useMemo, eg `useMemo(someImportedFunction, [])`
continue;
}
if (body.loweredFunc.params.length > 0) {
@@ -0,0 +1,30 @@
## Input
```javascript
function Component(props) {
const x = useMemo(someHelper, []);
return x;
}
```
## Code
```javascript
import { unstable_useMemoCache as useMemoCache } from "react";
function Component(props) {
const $ = useMemoCache(1);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = someHelper();
$[0] = t0;
} else {
t0 = $[0];
}
const x = t0;
return x;
}
```
@@ -0,0 +1,4 @@
function Component(props) {
const x = useMemo(someHelper, []);
return x;
}