From ce152a84bf8ca6a340fa72ebbf03ab1f14718063 Mon Sep 17 00:00:00 2001 From: Mike Vitousek Date: Thu, 15 Aug 2024 14:25:18 -0400 Subject: [PATCH] [compiler] Fixture to show ref-in-render enforcement issue with useCallback Test Plan: Documents that useCallback calls interfere with it being ok for refs to escape as part of functions into jsx [ghstack-poisoned] --- .../error.useCallback-ref-in-render.expect.md | 41 +++++++++++++++++++ .../error.useCallback-ref-in-render.js | 16 ++++++++ 2 files changed, 57 insertions(+) create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.expect.md create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.js diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.expect.md new file mode 100644 index 0000000000000..ad1c0e7c3fe3a --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.expect.md @@ -0,0 +1,41 @@ + +## Input + +```javascript +// @flow @validateRefAccessDuringRender @validatePreserveExistingMemoizationGuarantees + +component Foo() { + const ref = useRef(); + + const s = useCallback(() => { + return ref.current; + }); + + return ; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Foo, + params: [], +}; + +``` + + +## Error + +``` + 4 | const ref = useRef(); + 5 | +> 6 | const s = useCallback(() => { + | ^^^^^^^ +> 7 | return ref.current; + | ^^^^^^^^^^^^^^^^^^^^^^^ +> 8 | }); + | ^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef). Cannot access ref value at read $27:TObject (6:8) + 9 | + 10 | return ; + 11 | } +``` + + \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.js new file mode 100644 index 0000000000000..3fc086164d607 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useCallback-ref-in-render.js @@ -0,0 +1,16 @@ +// @flow @validateRefAccessDuringRender @validatePreserveExistingMemoizationGuarantees + +component Foo() { + const ref = useRef(); + + const s = useCallback(() => { + return ref.current; + }); + + return ; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Foo, + params: [], +};