Current section: Custom Hooks 36 exercises
solution

Hook Function

Loading solution

Transcript

00:00 Okay, so we want to have a useSearchParams hook. We'll make it right here, useSearchParams, and we're going to take everything that has to do with the search params. So we've got our state right here, our initializer, lazy initializer. We've got our useEffect and our setSearchParams. All of that stuff is going to come up here into useSearchParams and then we'll

00:19 return the search params and setSearchParams. We're going to add this as const to the end of it, and that's going to change the type information. So if I don't have the as const, then the return type of this is going to be an array of, let's see, where does the return type start?

00:38 It's basically, it sees it as an array of search params or a setSearchParams function, whereas this, by adding as const, it says, oh, okay, so this is literally an array that has the first item being the search params and the second item being a function that allows you to set the search params.

00:57 So it's not an array of any number of items that's one or the other. It's literally a read-only array of two items. The first is this, the second is that. So that as const is definitely needed on hooks like this. Okay, great. So with useSearchParams implemented now,

01:13 we can grab our search params and setSearchParams from useSearchParams. And like I said, not a lot of lines of code changed. If you look at the diff, there's really not a whole lot there. And it does still work. So this is functioning the way that it should. We're in a good place.

01:33 We can initialize in the right place and everything is working just fine. We literally just moved all of the code from the app into useSearchParams. And what's cool, what I think is cool about this is this is just like normal JavaScript stuff here. There's nothing really React specific that we did here.

01:53 We're just refactoring, moving some code. Now, it does come with some funniness of when you're starting to think about, oh, I wanna make this more generic and make it work in more places, which we're gonna talk about next. But the value of it being just JavaScript,

02:11 I think is a really beneficial aspect of the way that hooks work. So, all right, well done.