Hooks 11 exercises

Specify or Infer useMemo's Return Type

Fixing useMemo Typing Issues

In the starting code for this exercise, we're passing useMemo a function that returns an array of strings as a type argument. This is what we needed to do with useCallback, but it's incorrect in this situation.

const autoGeneratedIds = useMemo<() =

Loading solution


0:00 OK, let's take a look. This useMemo here, basically we're passing in a function that returns an array of strings here into this type argument. This is what we needed to do in the callback situation, but here it's actually incorrect.

0:15 If we cmd + click into useMemo itself, we can see that this factory here, this is the first argument. This is a function with no parameters that returns T. That T, the thing that we return from this factory, is the thing that gets put into the type argument there, and that, then, gets returned from useMemo itself.

0:36 If we take a look at that, if we remove this type argument, you notice that the errors go away completely. If we hover over useMemo, you can see that it's inferring string array in that slot.

0:48 If we instead just return an array of numbers, so return 1, 2, 3, for instance, then autoGeneratedIds is going to be an array of numbers, and useMemo has number array in its slot. We're in a pretty good position just by removing the type argument itself.

1:06 If we were to pass this in, then we would just need to pass in the thing that gets returned from this little factory here. There's another way you can type this too.

1:17 This might be useful if you have a function where it can return lots of different things or your function has many branches and you want to make sure that it's locked down what it's returning.

1:29 You could do this, where you type it slightly differently, you type the return type manually, which, as we've seen, makes sure that you're passing the specific thing or you're typing the exact thing that's it's returning because, just like in useState, you might get some excess property check errors if you don't do this.

1:48 My suggestion when you're using useMemo is to type it like this, or don't type it at all and let the inference take care of itself because it's pretty good without any type arguments.