Skip to content

[Typescript] hooks do not support null or undefined type in ref attributes #435

Description

@horarodriguezz

Describe the bug
In this issue, specifically in this commit, the possibility to pass null | undefined to the MutableRefObject was added.

After the library's rewrite in typescript, that issue got re-introduced and then solved in this issue/PR, in which the MutableRefObject became a Immutable RefObject.

In React 18 that was good, but with the React 19 changes for the useRef hook, the issue got re-introduced again.

In react 19, the MutableRefObject does not exists anymore, and RefObject is the unique interface for refs. Furthermore, the useRef hook must have an initial value.

This makes const ref = useRef() or const ref = useRef<HTMLDivElement>() to not work anymore. So we have to do this:

const ref = useRef<HTMLDivElement>(null); // The resultant type is RefObject<HTMLDivElement | null>

// or

const ref2 = useRef<HTMLDivElement>(undefined); // The resultant type is RefObject<HTMLDivElement | undefined>

Both of them conflict with the type of the RefObject of useResizeObserver:

Image

To Reproduce
Steps to reproduce the behavior:

  1. Open a React 19 + typescript project
  2. Create an empty feature with a div.
  3. Create a useRef constant, you will have to put null as initial value to pass it to the div
  4. Pass that ref object to the useResizeObserver hook

Expected behavior
The useResizeObserver hook and similar ones, probably all the ones that need a ref, should accept RefObject<TElement | null | undefined> to work well in React 19 with typescript projects


Desktop:

  • OS: Fedora Linux 44 (Workstation Edition)
  • Browser: Brave Browser
  • Version 1.91.175 (Chromium 149.0.7827.155)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions