Skip to content

[Compiler Bug]: ref.current === undefined, !ref.current are not allowed #34278

@iamakulov

Description

@iamakulov

What kind of issue is this?

  • React Compiler core (the JS output is incorrect, or your app works incorrectly after optimization)
  • babel-plugin-react-compiler (build issue installing or using the Babel plugin)
  • eslint-plugin-react-compiler (build issue installing or using the eslint plugin)
  • react-compiler-healthcheck (build issue installing or using the healthcheck script)

Link to repro

https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAwhALYAOhCmOAFAJRHAA6xRA9J0QCoAWeMEQDuEGAGswydkSJxCYHERyCwAJQRoA6uKlEAvEShgEmtPUxQANtcayieNEXqqh53ZLAA6OLBi0ygCEBkZWtsxsHHJuGlqeUr7+gYZErCD8AIZB6Q4AvuwO3EQAQlDKsUQAJhAIYJiAmAQ4MhwKmEoqauYAIrX1ykYmZlpMDk4usT19dEkwAXREIYOYVVp4mAhVkQ4xXVq9dTN+cylG6Vk5IPmFHMUCQi6mtI7EmUQBmdYAtGIw1lXyCCrABGmVMzE+kGq0yaLTkbQ6ky0AEFrJADv1UkNzKMOON6EEkWhUejpjhZvMcNtop13Ci0RAMUdkgszhlsrkOAVMA4AjhYMQADxVPAANy4AD52HkiCA8kA

Repro steps

(This may be by design, but still reporting it as it’s causing deopts in valid real-world code.)

In a codebase I'm adopting React compiler on, it's common to have this pattern to initialize refs:

const ref = useRef(undefined)
if (!ref.current) ref.current = something()
// or also:
if (ref.current === undefined) ref.current = something()

Right now, React Compiler deopts when encountering this pattern, mentioning “Cannot access refs during render”.

This is likely by design (everywhere in React docs, if you need to initialize a ref to nothing, you’re shown to use null). However, this pattern is still likely to be common in real-world codebases:

  • it’s pretty frequent in the codebase I’m working with (it’s a valid way to init, and it’s allowed by TS types)
  • it’s automatically emitted by React 19 TypeScript codemod when codemodding an empty useRef()

Just letting you know about a common source of deopts!

How often does this bug happen?

Every time

What version of React are you using?

19.1.1

What version of React Compiler are you using?

19.1.0-rc.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions