Skip to content

[BUG] React 19 ref cleanup is not respected #3360

@Malien

Description

@Malien

React 19 added ref cleanup functions, and deprecated the current "call with null on unmount" behaviour.

https://codesandbox.io/p/devbox/66jh5j

<div
  ref={(instance: HTMLDivElement) => {
    doAction(instance)
    return () => cleanup()
  })
/>

// mount: const cleanup = ref(div)
// unmount: clenaup()

vs

<div
  ref={(instance: HTMLDivElement | null) => {
    if (instance) doAction(instance)
    else cleanup()
  })
/>

// mount: ref(div)
// unmount: ref(null)

When the ref callback returns a cleanup function, the callback won't be called again with the null value. Instead the cleanup function will be called.

Motion components (motion.div) don't respect that convention and will always do the null thing.

<motion.div
  ref={(instance: HTMLDivElement) => {
    doAction(instance)
    return () => cleanup()
  })
/>

// mount: ref(div)
// unmount: ref(null)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions