TypeScript: React useRef Hook - Robin Wieruch

TypeScript: React useRef Hook - Robin Wieruch

A brief summary of how to use React’s useRef Hook for using a ref with TypeScript. First, a ref in React is mainly used to assign a HTML element to it. The assigned HTML element gives us imperative read and write operations on it which allows us to programmatically call functions. Take the following example for focusing an input element:

When using this function component with its useRef hook in TypeScript, you will most likely encounter an error. The best practice would be initializing the ref with null. In addition, you have to use a type argument to cast the ref to the type of HTMLInputElement respectively to the element where it is used as ref attribute:

Essentially that’s already it if you want to use an immutable ref for the HTML element. However, sometimes you want to use a ref as an instance variable to capture a value. For example, a ref could keep track of all click interactions:

Similar example but with a complex object where we extracted the type argument as interface:

If you happen to start with an instance variable that’s not initialized in React’s useRef Hook, but later in the code, then you would have to initialize React’s useRef Hook with null and use a union type based on the actual type and null for the type argument:

Essentially that’s everything you need to know about using TypeScript, React’s useRef Hook, and React’s ref. After all, either the ref is used as HTML element by leveraging the ref attribute on an element or as instance variable to keep track of a state which does not cause React to re-render. If you happen to find other variations of using React’s ref with TypeScript, let me know and I will add them to this guide.

Recommended articles