Advanced React Patterns State Initializer Solution
This course still contains valuable patterns in React, but doesn't cover React Hooks introduced in React 1.16.
Transcript from the "State Initializer Solution" Lesson
>> Kent C. Dodds: Let's see. Probably the best place to start is with our initialization here. So, when we initialize the state, we're initializing it to false by default, but now we want to be able to have people control that so we say this.props.initialOn. Okay, so now people can initialize it.
[00:00:23] That actually, that's all that we need to do to get it initialized the way that users of this want to have it initialized. But because we're accepting this from prompts, there are some use cases where they're not gonna wanna to initialize it. So we should have a default.
[00:00:38] So we'll add static default prompts, and this will be initial on will be false. In addition, we are now, we'll do that later. So, we've got that then. And we've got this done. And now Cody the koala bear wants us to add a reset method, so that people can reset within the render prompt.
[00:01:08] So we’ll say reset = this function, and instead of here, we’ll say this.setstate. And we can say on is this.props.initialOn. And then in the callback, we'll call this.props.onReset(this.state.on). Okay, cool. And now we need to add that to our, right here. Where Cody the koala bear is faithfully waiting for us.
[00:01:39] Restart, reset.
>> Kent C. Dodds: Great. That passes everything. So now folks can initialize it, and then within the render prompt, they can actually reset it themselves. And then,
>> Kent C. Dodds: Yeah. And so, this is totally fine if we just have one item of state. It's not a whole lot. But those two objects are totally identical, and if it's a bigger object, then it's kind of annoying to keep them in sync.
[00:02:10] So what I like to do is I create an initial state
>> Kent C. Dodds: Property on the instance. And then I reference this .initial state, and then stick that in there too. What I like about that is it not only, like, shortens the amount of code, which I don't care about so much.
[00:02:31] But it communicates what we're trying to accomplish, which I do care about. It communicates that this reset function is setting state to whatever the initial state was. And so, any time we decide, okay, we're gonna add a new item of state, we'll update this initial state and then the reset will work as expected automatically out of the box.