Skip to content

Commit a494195

Browse files
Clarify purity for null-guarded ref initialization
1 parent 4610359 commit a494195

3 files changed

Lines changed: 33 additions & 1 deletion

File tree

compiler/packages/babel-plugin-react-compiler/docs/passes/49-validateNoRefAccessInRender.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ if (ref.current == null) {
2929
}
3030
```
3131

32+
This exception only applies to the ref access pattern itself. Other validations
33+
still apply to the initializer expression. In particular, the initializer must
34+
still be predictable during render. Impure calls such as `Date.now()` or
35+
`Math.random()` continue to fail the `purity` rule even when they appear inside
36+
an allowed null-guarded ref initialization.
37+
3238
Error messages produced:
3339
- Category: `Refs`
3440
- Reason: "Cannot access refs during render"

compiler/packages/eslint-plugin-react-compiler/__tests__/ImpureFunctionCallsRule-test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,19 @@ testRule(
3434
makeTestCaseError('Cannot call impure function during render'),
3535
],
3636
},
37+
{
38+
name: 'Impure ref initialization still fails purity under a null guard',
39+
code: normalizeIndent`
40+
function Component() {
41+
const ref = useRef(null);
42+
if (ref.current === null) {
43+
ref.current = Date.now();
44+
}
45+
return <div>{ref.current}</div>;
46+
}
47+
`,
48+
errors: [makeTestCaseError('Cannot call impure function during render')],
49+
},
3750
],
3851
},
3952
);

compiler/packages/eslint-plugin-react-compiler/__tests__/NoRefAccessInRender-tests.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,20 @@ testRule(
1616
'no ref access in render rule',
1717
allRules[getRuleForCategory(ErrorCategory.Refs).name].rule,
1818
{
19-
valid: [],
19+
valid: [
20+
{
21+
name: 'allow null-guarded ref initialization',
22+
code: normalizeIndent`
23+
function Component() {
24+
const ref = useRef(null);
25+
if (ref.current === null) {
26+
ref.current = "stable";
27+
}
28+
return <div />;
29+
}
30+
`,
31+
},
32+
],
2033
invalid: [
2134
{
2235
name: 'validate against simple ref access in render',

0 commit comments

Comments
 (0)