What typescript type do I use with useRef() hook when setting current manually?

ReactjsTypescriptReact Hooks

Reactjs Problem Overview


How can I use a React ref as a mutable instance, with Typescript? The current property appears to be typed as read-only.

I am using React + Typescript to develop a library that interacts with input fields that are NOT rendered by React. I want to capture a reference to the HTML element and then bind React events to it.

  const inputRef = useRef<HTMLInputElement>();
  const { elementId, handler } = props;

  // Bind change handler on mount/ unmount
  useEffect(() => {
    inputRef.current = document.getElementById(elementId);
    if (inputRef.current === null) {
      throw new Exception(`Input with ID attribute ${elementId} not found`);
    }
    handler(inputRef.current.value);

    const callback = debounce((e) => {
      eventHandler(e, handler);
    }, 200);

    inputRef.current.addEventListener('keypress', callback, true);

    return () => {
      inputRef.current.removeEventListener('keypress', callback, true);
    };
  });

It generates compiler errors: semantic error TS2540: Cannot assign to 'current' because it is a read-only property.

I also tried const inputRef = useRef<{ current: HTMLInputElement }>(); This lead to this compiler error:

Type 'HTMLElement | null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.

  Type 'null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.

Reactjs Solutions


Solution 1 - Reactjs

Yeah, this is a quirk of how the typings are written:

function useRef<T>(initialValue: T): MutableRefObject<T>;
function useRef<T>(initialValue: T|null): RefObject<T>;

If the initial value includes null, but the specified type param doesn't, it'll be treated as an immutable RefObject.

When you do useRef<HTMLInputElement>(null), you're hitting that case, since T is specified as HTMLInputElement, and null is inferred as HTMLInputElement | null.

You can fix this by doing:

useRef<HTMLInputElement | null>(null)

Then T is HTMLInputElement | null, which matches the type of the first argument, so you hit the first override and get a mutable ref instead.

Solution 2 - Reactjs

I came to this question by searching how to type useRef with Typescript when used with setTimeout or setInterval. The accepted answer helped me solve that.

You can declare your timeout/interval like this

const myTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)

And to clear it and set it again, you do it as usual:

const handleChange = () => {
  if (myTimeout.current) {
    clearTimeout(myTimeout.current)
  }
  myTimeout.current = setTimeout(() => {
    doSomething()
  }, 500)
}

The typing will work both if you're running in Node or in a Browser.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJPollockView Question on Stackoverflow
Solution 1 - ReactjsRetsamView Answer on Stackoverflow
Solution 2 - ReactjsLuisusView Answer on Stackoverflow