Current section: Shared Context 36 exercises
solution

Context Hook

Loading solution

Transcript

00:00 All right. So what's going on is because we're not wrapping this in our provider, we're not doing any of the provider stuff in here. In fact, this is an unused variable. So all of the stuff that's responsible for listening to pop state and for setting search

00:15 params like that set search params function, all of that stuff is not being used. And so, while we may be all accessing the same type of thing and able to set the global search params, that works out just fine. And we're able to get the initial URL search params. So if I were to

00:35 say query dog, like that's filtering fine. But when we try to update, it's just updating the URL and not actually able to feed into our search params that we're using for our UI. So I find

00:52 this actually quite a lot that my context providers do not make sense to have a default value. And instead, I say no for my default value. And then down here in my context consumer,

01:10 I find that it's really annoying to have to do null checks for all of these uses of the use search params, because now it could be search params tuple or null. And that absolutely can be null because we're not rendering our provider yet. And so my use search params hook here is

01:28 going to check if there's no context. And if there's not, then we're going to let people know, hey, use search params must be used within a search params provider. And so now we're blowing up but at least we get a nice error message explaining exactly what I just said. So what

01:47 we need to do now is add the search params provider and close that off. And now we are within a search params provider. And as I type, it is updating again, we fixed it. Good job

02:01 caterpillar. There we go. And uncheck that. Oh, it's so cool. All this good stuff. So most of the time, not always, for sure, there are situations where having a default makes sense. But most of the time, I find myself setting this to null, and then having the context do the null check for me

02:20 so I don't have to do it all over my code base. So there you go. That is handling the default in a more expert way.