So before I show you how it happens, let's look at some console logs. Here we have a component which does pretty much the same thing, and let's see what happens when we click the plus button. We have an onclick event handler, and we call setcounter. Let's minimize this with the update function. Here we have a console log of update, and here we have a console log of render. And when we click the increment button, let me just move this over here, we render first, and then we call the update function, which is exactly the opposite of what we expect, right?
We expect it to update the value of the hoop and then re-render, but it's the other way around. So let's see how this happens. So when we call set counter, there's actually another linked list attached to each of our hooks, and this is the update queue. So every update that we perform on our state is not performed immediately. It's added to the queue, and it will be processed during render. Let's see how this works.
So we call set counter, we pass in the update function. All React does is put this update function in a queue, and then it schedules a rerender, which means it turns on some kind of flag that says, this component needs to be rerendered after we finish all of the updates. Now we might have more updates. We might update this hook again. We might update other hooks. We might call the parent component callback, which will update some stuff. We might dispatch some Redux action that will update other components. And all of these updates will be queued. And then at some point, and we will discuss when it happens. React decides to rerender the entire component tree, or not the entire component tree, the components that were scheduled for rerender from top to bottom. So according to the hierarchy of the component tree. And as I mentioned, we will discuss when this happens later. And now, and only now, when we actually re-render the component, React looks at what we call useState. When we actually call useState, during the render, React checks to see if there are any updates that are queued, and only then it will perform these updates. So during render, while we call useState of this specific hook, React will look and see, okay, there's an action, let's perform it, this action updates the hook to one, and if there are other actions, it will perform them sequentially until we exhaust the queue. So let's add another console log, minimize this. So now, as you can see, we added another console log after useState. So we console log before useState, after useState, and during the updater function, and let's do some updates, clear the log, and when we click plus, you can see that the first thing that happens is that we render. The second thing is that we call update, so which means that during the call to useState, React runs the updater function, and only then we call after useState, which is here.
Comments