Are you getting a crazy amount of errors from TypeScript about your React useRef typing?
In today’s short article, I will go over how to use define your useRef hook with TypeScript.
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:
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.
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.