Current section: State Initializer 30 exercises
lesson

Intro to State Initializer

Loading lesson

Transcript

00:00 The state initializer pattern is barely a pattern except for this one catch. So if you ever need to do this, it's important for you to learn about this so that you avoid this problem. All right, let's talk about what this thing is at all. The state initializer pattern

00:14 is a way to initialize and reset the state of a component in a predictable way. So here's our use counter. We have our state, we have our increment. And if I wanted to initialize the state, then here's my initial count. It's not a prop because it's not a component, but it's an option, I

00:31 suppose. So here's my initial count. I'm going to pass that there. So that's the initialization. But a part of the state initialization pattern is being able to reinitialize a hook without having to unmount the component and mount it again or something. And so here we're going to provide a

00:47 mechanism for resetting the state to reinitialize it. And we're going to pass that initial count. The problem is that if that initial count is really the initial count, and that's what you reset to, then you want to prevent changes to this prop from impacting what it resets to. And so

01:06 to do that, you use a ref, and then you never update that ref. And that way, on that initial render, the initial time this is called, you're going to initialize that ref. And then you can use that for the initial value of your state. And then your mechanism for updating that or

01:24 resetting it will also reference that initial value. That way, even if the hook is re-rendered with a different initial count, you ignore it because it is initial. And that's the semantics of the thing. So it is important. This one is a pretty quick one. Like I said, it's barely a

01:42 pattern at all, except for that catch. It is used occasionally as something that you may want to have in your arsenal. So that's why we're doing this exercise. So let's get into it.