diff --git a/compiler/crates/react_compiler_validation/src/validate_no_ref_access_in_render.rs b/compiler/crates/react_compiler_validation/src/validate_no_ref_access_in_render.rs index 22708b1dbb48..b430623e5276 100644 --- a/compiler/crates/react_compiler_validation/src/validate_no_ref_access_in_render.rs +++ b/compiler/crates/react_compiler_validation/src/validate_no_ref_access_in_render.rs @@ -185,10 +185,7 @@ fn join_ref_access_ref_types(a: &RefAccessRefType, b: &RefAccessRefType) -> RefA loc: None, ref_id: None, }, - (_, RefAccessRefType::RefValue { .. }) => RefAccessRefType::RefValue { - loc: None, - ref_id: None, - }, + (_, RefAccessRefType::RefValue { .. }) => b.clone(), (RefAccessRefType::Ref { ref_id: a_id }, RefAccessRefType::Ref { ref_id: b_id }) => { if a_id == b_id { a.clone() diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.expect.md new file mode 100644 index 000000000000..c08466e1543a --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.expect.md @@ -0,0 +1,34 @@ + +## Input + +```javascript +// @validateRefAccessDuringRender +function Component({cond}) { + const ref = useRef(null); + const x = cond ? ref : ref.current; + return ; +} + +``` + + +## Error + +``` +Found 1 error: + +Error: Cannot access refs during render + +React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef). + +error.invalid-ref-value-phi-with-ref.ts:4:25 + 2 | function Component({cond}) { + 3 | const ref = useRef(null); +> 4 | const x = cond ? ref : ref.current; + | ^^^^^^^^^^^ Cannot access ref value during render + 5 | return ; + 6 | } + 7 | +``` + + \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.js new file mode 100644 index 000000000000..73c6cf384589 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-value-phi-with-ref.js @@ -0,0 +1,6 @@ +// @validateRefAccessDuringRender +function Component({cond}) { + const ref = useRef(null); + const x = cond ? ref : ref.current; + return ; +}