Skip to content

[Compiler Bug]: ref initialization using === null doesn't work with impure functions #35973

@simarmol

Description

@simarmol

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-hooks (build issue installing or using the eslint plugin)
  • react-compiler-healthcheck (build issue installing or using the healthcheck script)

Link to repro

https://eslint-online-playground.netlify.app/#eNqlVM1um0AQfpXRXupExNydOmqlJGpOrZKqPQQfKAx442UX7U/iyELqQ/QJ+ySdYbENbtRLhQ1o99tvvvlmhp1wtkhxmzetwvmT24qFkE1rrIcdBIf3WCX8vKkqLDx0UFnTQCYs5oXPxGWm+aqCLrw0Gr4EizeRbHYGu0wD8L8w2nmwWMFyIJ3poNQZHQeQFcxoa14Ea1F7WC6X0O/G8wBpCodFKNZYbKA06PQ7D97KukbbU0tND12ijacmlKS4FwvQ8Y0YTfBOlgh+jUdy6QGtNdYx6JRAmxaJpt/xwWp4X8rnq5YyptB08sXYjXuf8iJFojh8sfa7pgdV5Jixr/D75y/mdmCDQsiVMi8uAYJI/xrXbu/ubx5GrkaCE1//z9Npcte5x7k2L7OzS/amL+7F2piNSwddvS2wRouDifw49MWMRC2v9tyszFA3KVPPMtGYoD2WkFO7JOO4UWmXwOOKX0+NpS48WPtDmWKD5dRctpYUPHgS35ufWwpV9v6O3YwOj+z8fsC+aenjoPijX0Vr+whDikenovyx4qOGo1CRCHRKaj8n8krWNGLHCet9/sQ278cqYi9aFWqpL0Z1GEYNt/3BEqs8KJLKEgbXK6nQLWhJnJ+n5/Pdk0tonBPv6LftMrFKIi5yE3K3H+N9hMVYUDfAVa7rkNf4uWXv+FhcJ6LcOrR/rwNg0eTf0DraWFAQRZ45rv4R4UywBX59bZEBjSmpUBMAU9xiTuZyUjugVBY07QEPwrh14tv+ydUeC5mkNzQyZ0k2czeP4k2RPJxv4WIcvq8uqa5tXmzIGKqo0VTT+LETnnKKhydZZaLE52ts+QOlC4l9gEFpJj7EuqdPQ9wTx/Z98c/NN5tmjD8Mbie6P5C2ABI=

Repro steps

See the link for playground.

Basically, the ref-in-render rule doc states that this very specific access is allowed:

Example 1:

// ✅ Lazy initialization of ref value
function Component() {
  const ref = useRef(null);

  // Initialize only once on first use
  if (ref.current === null) {
    ref.current = expensiveComputation(); // OK - lazy initialization
  }

However, if expensiveComputation is impure, it still fires.
Example 2:

  if (ref.current === null) {
    ref.current = Date.now(); // purity rule

And of course, useState(() => Date.now()) is fine. The react docs say

// It only runs once when the hook is called, so only the current date at the
//    time the hook is called is set first.

Between those three, I'd expect my second example to be valid, but it's not?

How often does this bug happen?

Every time

What version of React are you using?

19.0.1

What version of React Compiler are you using?

1.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugType: Bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions