Advanced React Patterns Advanced React Patterns

State Initializer Pattern & Exercise

Check out a free preview of the full Advanced React Patterns course:
The "State Initializer Pattern & Exercise" Lesson is part of the full, Advanced React Patterns course featured in this preview video. Here's what you'd learn in this lesson:

Kent discusses how the state initializer pattern allows you to initialize the state and give the component the ability to reset the state.

Get Unlimited Access Now

Transcript from the "State Initializer Pattern & Exercise" Lesson

[00:00:00]
>> Kent C. Dodds: Okay, so this one is state initializers. It's actually a pretty simple one. So there are some situations, and this isn't render prop-specific. This could apply to any components, but it fits nicely in our render props, so we're just building on top of what we have. But there are some situations where you might want to have a- Hehre, let's go to-

[00:00:29]
>> Kent C. Dodds: Yeah, state initializers. You get your component in some sort of state. You wanna reset that state. We've got this reset button. Set everything back to the initial state. And in general, you not only want to be able to reset things back to an initial state, but you also want to start things up in an initial state.

[00:00:51] So here we could have our initial-on be true and then when this reloads it'll start out. Well, it should start out and what the junk? Right, we haven't implemented that yet. Let's go back to the finished example. Change this to true. And that will initialize our state to a certain spot.

[00:01:18] And so, in downshift we have an initial, a state initializer for every piece of state. There are only actually four pieces of state and considering the size of downshift and the utility of it, it's kinda surprising that that's all you need. But yeah, we allow you to pass in the initial value for any of those pieces of state.

[00:01:39] So when it renders, the menu starts is open, or whatever else you want. And then we also provide, I'm pretty sure we provide a reset mechanism. So, that is the problem that we're trying to solve is allowing people to initialize things and also reset stuff to their original state.

[00:01:59] And to do that, we need to make a couple of changes. So with that, feel free to jump into the exercise. And I will also do it. So we'll go into our test number seven. Swap these.
>> Kent C. Dodds: And run npm t to start up the test.
>> Kent C. Dodds: And we'll get bunch of errors, because reset is not a function.