All Articles

Strongly Type useRef with ElementRef

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

Using useRef with native elements can be a bit of a pain. You need to specify the type of the element you're targeting, but it's not always clear what type you should be using.

import React, { useRef } from "react";

const Component = () => {
  // What goes here?
  const audioRef = useRef<NoIdeaWhatGoesHere>(null);

  return <audio ref={audioRef}>Hello</audio>;
};

A simple solution is to hover over the type of ref to check what it accepts:

import React, { useRef } from "react";

const Component = () => {
  // What goes here?
  const audioRef = useRef<HTMLAudioElement>(null);

  return <audio ref={audioRef}>Hello</audio>;
(property) React.RefAttributes<HTMLAudioElement>.ref?: React.Ref<HTMLAudioElement> | undefined
};

But there's an easier way.

What is ElementRef?

You can use ElementRef, a type helper from React, to easily extract the type from the element you're targeting.

import React, { useRef, ElementRef } from "react";

const Component = () => {
  const audioRef = useRef<ElementRef<"audio">>(null);

  return <audio ref={audioRef}>Hello</audio>;
};

This even works with custom components that use forwardRef. You can use typeof to pass them to ElementRef, and it'll extract the type of the element that the component is forwarding to.

import { OtherComponent } from "./other-component";
import React, { useRef, ElementRef } from "react";

// Pass it in via typeof!
type OtherComponentRef = ElementRef<typeof OtherComponent>;

const Component = () => {
  const ref = useRef<OtherComponentRef>(null);

  return <OtherComponent ref={ref}>Hello</OtherComponent>;
};

If you're using the previous solution (with HTMLAudioElement or HTMLDivElement, etc.), there's no reason to change it. But if you're ever unsure what type to use, ElementRef is a great helper.

And if you want more tips like this, check out my free React and TypeScript beginner's course. There are 21 interactive exercises packed with TypeScript tips and tricks for React apps.

Matt's signature

Strongly Type useRef with ElementRef

Cursor Rules for Better AI Development

Finding existing community .cursor/rules for TypeScript lacking, I'm sharing my own set to hopefully kickstart a discussion on what makes effective AI coding guidance. These rules focus purely on TypeScript language features, documentation, structure (like Result types), teaching the AI specific nuances (like noUncheckedIndexedAccess), and practical habits, rather than specific frameworks. I also distinguish between shareable, project-specific Workspace Rules (versioned in Git) and personalized Global Rules (living in your IDE) to tailor the AI to your individual style and workflow. You can download my current ruleset using the link in the original post.

Matt Pocock
Matt Pocock