Current section: Managing UI State 29 exercises
solution

Init Callback

Loading solution

Transcript

00:00 All right, let's make our function, getQueryParam, and we're going to take this stuff, move it up, return initial query, and then we can put this right in there. Dun-dun-dun-dun. This is functionally equivalent to a function. Call the function.

00:17 But, yeah, we just stick the function in there, and now we don't have to worry about this running. So we could add a console.log, hello, and if we initialize this to have a query, cat, dog, that totally works, no problem. If we look at our console right here, we get hello,

00:36 but as we make changes, we're not going to get that hello again. And, yeah, if we actually change this to actually call the function, then you notice that's going to call every single time, and that's unnecessary because we only care about the first initial time. So that's what the optimization is for.

00:53 It's to just make it so that you're not computing the initial value a whole bunch of times. You just compute it the one time that it's actually used, and then the rest of the times, other renders, the function's not called.

01:09 We could also, just for the fun of it, stick this right in here directly. That also works just fine, and I sometimes do that as well, just stick the function right in there. You're going to be allocating space and memory for that function. It'll get garbage collected. It'll be fine.

01:26 Not a big problem either way, but in this case, we're extracting it because we're actually going to be using this function pretty soon. So there you go. That is the lazy initializer for useState.