Current section: State Initializer 30 exercises
solution

Stability

Loading solution

Transcript

00:00 So, what we need to do is make sure that useToggle has access to the initial on in such a way that it never changes. So what we're going to do is set useRef from React, whoops, our coding assistant is being

00:17 a little overeager, but now we have our initial state, we're going to say .current, there we go, for that initial state. And this initialState.current will handle that as well. And so now, because we never update the initialStateRef, and actually it might make sense to call this

00:36 initialStateRef, because we never actually update that ref.current value, it's always going to be what we set it to when this was first initialized. And so, that solves our problem. I can switch this to false, I can go back, I can reset, and it's doing exactly what it should.

00:53 And so, no matter whatever people outside of our useToggle hook are doing, this initial value cannot be changed. They could reset it with a key if they wanted to, but when you render this initially, this initial value will not be changed. And I think that's a valuable, useful feature.

01:10 I am using this in Downshift, and I've seen it in other libraries as well. So, this is the state initializer pattern. Good job.