Current section: Managing UI State 29 exercises
Problem

Initialize State

Loading exercise

Transcript

00:00 A lot of times in UIs like this, you want to have the UI be shareable. And the way that we share things on the web is with the URL. And so if I wanted to design this URL so that it makes things shareable,

00:14 then I might add a query and cat dog, and that would have cat and dog in here. But that's not working right now because we don't have our initialization coming from the URL. We initialize it as an empty string.

00:32 So when this page is loaded, React is like, okay, let me run everything. So we've got our useState. This is initialized as an empty string, so we'll render this UI with the empty string. But we want to initialize it based on the query and the query string up here. So this is how you retrieve that.

00:49 You make URL search params from the window location search. And then you use this params.getQuery, which will give us our initial query. If that doesn't exist, it could be null. There may be no query. Then we can fall back to an empty string. That makes sense. But then we can use this initial query in our useState call.

01:08 So this should be pretty quick, but it will allow us to at least land on the page and have those elements in our query, which would be a good thing. So have fun.