Hooks 11 exercises
solution

Typing the useRef Hook

Let's start by using CMD + Click to check out useRef's type definitions.

There are actually three definitions for it, but for this exercise we'll be focusing on the one where we don't pass anything to it:


function useRef<T = undefined>(): MutableRefObject<T | undefined>;

As

Loading solution

Transcript

0:00 Let's take a look at useRef in terms of its type definitions. We can Command-click on useRef. Whoops, there we go, and now zoom out a little bit so we can see it.

0:09 You'll see that there are actually several definitions. There are three definitions for it, and over the next few exercises we're going to get to know them. This one, we're not passing anything to it. We've got a T that's just here, and we get back a MutableRefObject with T or undefined.

0:26 What we can see, then, is if we hover over useRef, we've got a type argument there, and it's currently typed as undefined. If we pass it something, then I assume it's going to start behaving properly.

0:39 Yes, we can pass a string to it. Now the id is going to be typed as React.MutableRefObject string or undefined, and id.current is now string or undefined.

0:51 This is good. This means that if we, for instance, were to pass a number here, then this would error properly because string is not assignable to type number. It means, then, that we can get this working and id.current can be assigned its proper value.