Hooks 11 exercises
solution

Specifying types for useState

As we saw in the last exercise, we can pass the Data type into useState:


export const Component = () => {
const [data, setData] = useState<Data>();

If we aren't passing in an initial value, we can simply pass a type argument.

This means that data will be inferred as `Dat

Loading solution

Transcript

0:00 As you might have figured out from last time, we can pass in data into useState here. What this is going to do is -- it's interesting -- because we're not passing something initial into here, we can actually just pass in a type argument. Then data will be inferred as Data or undefined.

0:20 If I pass something inside here...Let's say I want it to be Data or null, for instance. Then this is actually not going to be allowed because when we specify Data inside here, the only thing we can pass in is Data itself, like the actual thing that we specify. We'd have to do id 123 name Matt.

0:42 This means then that this will work. This is an alternative way. If you want this to be Data or undefined or T or undefined, the thing you pass in or undefined, then you can just pass in nothing here.

0:53 Though the other way to do this, actually, if you want to be more specific -- I'm not sure whether this is better or not, but it's an alternative way of achieving the same effect -- is you can actually do Data or undefined in the type argument and then pass in undefined manually.

1:09 You can also do this if you want to, Data or undefined. This is useful if you want to explicitly use null as your type. You have Data or null inside there.

1:20 This is slightly different from functions that you might have seen before, which is useState uses a couple of what I'd call function overloads to basically get around the fact that sometimes you want to pass in stuff and sometimes you don't want to pass it in an initial value.

1:35 Of course, if we do pass in our initial value, blah, blah, blah and then name Matt, then that's going to be inferred as basically just Data here. It's not going to be Data or undefined because we're passing in this initial value.

1:48 We're go. This is a good demonstration of what useState does to try to make your life just a little bit easier. Sometimes it can be confusing when you're looking at it and you're going, "What is TypeScript doing here?"