Linguine Code

How to use React useRef with TypeScript

Are you getting a crazy amount of errors from TypeScript about your React useRef typing?

React useRef  incorrect type definition messages.

In today’s short article, I will go over how to use define your useRef hook with TypeScript.

The solution

Using TypeScript with useRef hook

Let’s go over it really quickly.

I’ve imported the React useRef, and React useLayoutEffect tooling.

If you’re not familiar with React useLayoutEffect, I recommend you go read a previous article to learn more about it: When to use React useRef and useLayoutEffect vs useEffect

In line 4, I’ve initiated a useRef hook and added an open and close bracket.

Inside that bracket I used the HTMLHeadingElement type definition because I’m attempting to get a header element reference.

Make sure to use the correct HTML type definition for the right HTML element.

Here’s a list of other HTML type definitions:

  • HTMLDivElement
  • HTMLButtonElement
  • HTMLBRElement
  • HTMLLinkElement

And I initialized the value with null.

This is important to make sure you avoid those crazy amount of confusion error messages.

I then put the h1Ref variable inside the ref property of my H1 element.

Console logging useRef DOM reference object

React useRef will return an object with a property key called current.

It will first return a null value on the first render.

After the useRef hook fires, the React render lifecycle will kick in again and update the h1Ref variable will have element reference object.

Make sure to use the useLayoutEffect whenever you’re doing any work with the DOM reference object.

GitHub Source link