Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[compiler] Check ref access in useState initializer function #32506

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,9 @@ function validateNoRefAccessInRenderImpl(
}
}
for (const operand of eachInstructionValueOperand(instr.value)) {
if (hookKind != null) {
if (hookKind === 'useState') {
validateNoRefValueAccess(errors, env, operand);
} else if (hookKind != null) {
validateNoDirectRefValueAccess(errors, operand, env);
} else {
validateNoRefAccess(errors, env, operand, operand.loc);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

## Input

```javascript
// @validateRefAccessDuringRender
function Component(props) {
const ref = useRef(1);
const [state] = useState(() => ref.current);
return <div>{state}</div>;
}

```


## Error

```
2 | function Component(props) {
3 | const ref = useRef(1);
> 4 | const [state] = useState(() => ref.current);
| ^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (4:4)
5 | return <div>{state}</div>;
6 | }
7 |
```


Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// @validateRefAccessDuringRender
function Component(props) {
const ref = useRef(1);
const [state] = useState(() => ref.current);
return <div>{state}</div>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ const tests: CompilerTestCases = {
}
`,
},
{
name: 'Ref access in useEffect hook',
code: normalizeIndent`
function Component() {
const ref = useRef(1);
useEffect(() => {
ref.current = 2 * ref.current;
}, []);
return <div>Hello world</div>;
}
`,
},
],
invalid: [
{
Expand All @@ -122,6 +134,22 @@ const tests: CompilerTestCases = {
},
],
},
{
name: '[InvalidInput] Ref access in useState initial value function',
code: normalizeIndent`
function Component(props) {
const ref = useRef(1);
const [value] = useState(() => ref.current);
return value;
}
`,
errors: [
{
message:
'Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)',
},
],
},
{
name: 'Reportable levels can be configured',
options: [{reportableLevels: new Set([ErrorSeverity.Todo])}],
Expand Down