Current section: Multiple Hooks 16 exercises
Problem

All useState Hooks Are Overwriting the Same State

Transcript

00:00 So right now our implementation is pretty naive. We're just saying, here's our state, here's our set state. We're setting those values and everything. But yeah, that's not going to work, because we've got multiple of these. So I guess we could say state 1 and set state 1, and then state 2 and set state 2, and just do that a million times.

00:19 But that sounds awful. I hate that. We're not going to do that. So instead, we need to have some sort of bucket that is like, here is all of the state. And then we need to have some mechanism, some ID to identify our multiple calls of useState. That ID is going to be when they're called.

00:39 And so we're going to have a hook ID, which will just be a number that we increment every time useState is called. The problem is that this could just increment into infinity. So every time we render, we're going to reset that to 0. And so then as we increment it, we'll be able to know, OK,

00:55 so for this render, we're looking for a hook ID of 0. And now we're looking for a hook ID of 1 and 2 and so on and so forth. And that will allow us to know which state value we need to update when setState is called.

01:13 And it will allow us to know where to get our state that we return when useState is called. So you need to make a hook index. And from that, you will derive your hook ID. You're going to need to create that bucket of state. And from that, you will pull the state based off of the hook ID. So it's going to be fun.

01:32 And oh, and also don't forget to update the render that is at the bottom there. That way, we're resetting the hook ID or the hook index to 0. So every time we render, we're starting at the start. So this should be a good time. See you when you're done.