Hooks 11 exercises

Properly Typing useState

Let's now look at useState, one of React's most important hooks.

Consider this Tags component which would be used to add tags to the UI:

export const Tags = () => {
const [tags, setTags] = useState([]);
return (
{tags.map((tag) => {
return <div key={ta

Loading exercise


0:00 Let's now look at useState, one of Reacts most important hooks. Let's say we have a component called Tags here. With tags, we have a bunch of different tags that we're basically adding to the UI.

0:12 We have tags and setTags and it goes for a useState, which is an empty array. That's the starting setup of this component. For each tag, we're going to map over it and return a div with a key of tag.id. The tag value is going to be the thing that's displayed in the UI.

0:30 Then we've got a button that basically, when you click the button, it adds a new tag to the end of the array. We can see we're doing setTags and passing in a bunch of the existing tags but then also passing a new one.

0:43 Except, as you can see, we have a bunch of type errors here. This useState up here, it's not understanding what type it's supposed to be. If you look at tags here, it's actually never array here. What?

1:02 If we hover over useState, you can see that useState is being inferred as never array because the thing that we're being passed in here is just an empty array, and TypeScript infers an empty array as never array.

1:16 This means that these tags, then, just don't work at all. It means that we're not getting inference on tag.id, tag.value, and we can't set tags here. Your task is to try to figure out how we can make this useState understand that it's supposed to be a type of an array of object with ID number and value string.

1:41 The thing you're going to find useful here is passing type arguments to functions, and I'll link that below. Good luck.