Current section: Managing UI State 29 exercises
solution

Initialize State

Loading solution

Transcript

00:00 Alright, so we've got query equals dog plus cat, that should be, or cat plus dog, that should be cat space dog, right here, and these two should be checked when it's working. So with this, we need to create a params variable that's based on URL search params.

00:15 So let's make params, new URL search params based on the window location search. And then from that, we can say params.get query, and we can fall back, if it ends up being null, we can fall back to an empty string. And that, actually, is it, we're done.

00:33 So save that, we got cat space dog, everything's working awesome. This is not typically how you're going to do this in a real application, like grabbing it from window location search. Of course, it doesn't run on the server, because there's no window location on the server, and things like that. You're going to be using a router in any real application that you're using, and that router

00:53 is going to give you a search params hook or something like that. You're not typically going to be doing things directly like this, you'll probably want to use a router for this, but this is how you do it, and now we are able to initialize our state dynamically based on what the current URL is.

01:12 So I could say, caterpillar, and I must have misspelled it, yep, I think I did. There we go. So we can initialize that based off of the URL search params, and then it falls back, of course, to an empty string.

01:29 So there you go, initializing with useState and pulling it from the search params, pretty common thing to do.