Transcript
00:00 So let's take a look at what's going on. We're trying to render the toggle button. If I go to the toggle button, it's trying to use the toggle context. But the toggle context could be null. In fact, we initialize it to be null. And so when we come around here and say, OK, let's destructure these properties, we're destructuring it off of null. And TypeScript can't help us because we told it, hey,
00:19 I know better than you. We're going to get rid of that first and let TypeScript do its job by helping us out and saying, hey, this could be null. And then we're going to, because I don't like having to deal with that, that'd be super annoying. You have to say context equals that. And if there's not context, then what do I render?
00:38 I don't even know what I render. Probably throw an error, but just a more helpful one. So instead, whenever you want to do a reusable thing, you make a function. And we're going to make a function called useToggle. It's a hook because it's a function that uses another hook. So we're going to get our context from useToggleContext.
00:57 And then if that context does not exist, we'll just say if there's no context, then we're going to throw a new error that says toggle must be used within a toggle provider. Or maybe to be more clear, because exactly what we're trying to do here, we're going to say toggle context not
01:16 found, all toggle components must be rendered in a toggle. That's pretty descriptive, nice and helpful error message. And then if that context does exist, then we'll simply return it.
01:32 And then here, for these three, we'll just say useToggle. And now TypeScript is happy because we've handled the null case. And our users will be happy because we handled the null case also and gave them a much more useful error message. Oh man, I didn't realize that all toggle components must be rendered within a toggle. Let me go fix that.
01:51 So we'll go over here and we'll say, OK, toggle right there. And stick toggle button in there. And now, would you look at that? It works, hooray. And then, of course, we can do all of our other toggle components or toggle on and toggle off and all that stuff that we had before.
02:09 But the point is that the error message is much more useful. And our ability to consume the context is a lot easier. So in my compound components, I pretty much always do this. I'm not really exporting this. There could be a use case for that. I don't need to export it. And so it's not like I'm just doing this
02:29 for to keep myself happy and stuff. It's to make my users have a much better error message and make it easier for me to consume it properly.