We use them all the time, and we think we know state hooks work (useState, useReducer). But under the hood, as expected, things are not what you imagine. This talk is about update queues, batching, eager and lazy updates, and some other cool things learned from looking at Hooks source code. It also contains practical takeaways that will help you better understand and debug your code.
We Don’t Know How React State Hooks Work
AI Generated Video Summary
This Talk provides an introduction to React Staytools, explaining how to use the state and setState function to update a counter. It also delves into the inner workings of React rendering, discussing the update queue and re-rendering conditions. The Talk concludes by mentioning the different modes of updating and triggering re-renders in React, and encourages further exploration of the source code and discussion in Discord.
1. Introduction to React Staytools
Hi! This is We Don't Know How React Staytools Work. My name is Adam Klein and I'm broadcasting from Tel Aviv, Israel. Let's take this code, which uses a state that's initialized to 0, which is a counter. And we have a button that has an onClick event handler. The onClick event handler calls setCounter, which is the setState function, and passes in an update function, which increments the value by 1. Let's see what happens when we call setCounter.
Hi! This is We Don't Know How React Staytools Work. My name is Adam Klein and I'm broadcasting from Tel Aviv, Israel.
Let's take this code, which uses a state that's initialized to 0, which is a counter. And we have a button that has an onClick event handler. The onClick event handler calls setCounter, which is the setState function, and passes in an update function, which increments the value by 1.
Let's see what happens when we call setCounter. Now, you probably know that React manages the state of the hooks for us outside of the component. And what I used to think that happens is that we call setCounter. React takes the current state of the hook, which is in our case 0, calls our update function which returns 1, and updates the state of the hook to the new value, which is 1. And then re-renders our component. And the render function calls useState which gets the new value, which is 1, and the component re-renders. This is pretty straightforward, except that it's wrong.
2. Understanding React Rendering
Let's see what React really does. Every hook has its own update queue where React keeps all of the pending actions. When we call setCounter, React adds the update to the queue and schedules a re-render. React decides to re-render based on certain conditions.
So let's see what React really does, and this is a simplified version. So in fact, every hook has its own update queue where React keeps all of the pending actions to this hook. So when we call setCounter, React just adds the update to the queue. It adds an action. What is the action? Whatever we passed inside setState, which could be either a function or a value, or in case of reducers, it's the action that we dispatched. And then it just schedules a re-render, which means it flips some flag that says this component needs to be re-rendered. And there might be more updates to this hook, or other hooks, or hooks in other components. And eventually React decides to re-render. And then it re-renders all of the components according to their order inside the tree. So when does this React decide to re-render? We'll talk in the last part of this talk.
3. Understanding React Rendering
So eventually we re-render. React performs updates inside the queue of the hook. It's called a lazy update. There's also an eager mode. React decides to re-render based on event handlers. Updates are queued and then re-rendered. Async event handlers trigger immediate re-renders. We're done. Open the source code, ask questions in Discord. Have a good conference!
So eventually we re-render. We call useState during render. And only then, during render, React will perform the updates inside the queue of this hook. So it takes the first action, gives it the previous value, gets back the new value, which is 1. And if there are more actions, it continues to the next action and performs them one by one. And then goes to the next statement in our render function. So this is called a lazy update. Which means, React only does the work when the result of the work is needed. And everything I say about useState holds for useReducer because in fact, under the hood, useState uses useReducer. So it's the same mechanism behind the scenes.
Now you might be wondering what about render bailout? So if React only calculates the new state during render, how can it bail out of render if the new state is different than the old state? So in this case, we have a state that starts from zero. And if we update it to zero, you would expect React not to rerender our component. So it turns out there's actually another step that sometimes React decides to take for this optimization, which is to eagerly calculate the new state immediately when we call the setState function. And then if the new state is the same as the old state, it doesn't schedule a rerender. And if they are different, then it continues normally, but it caches the result of the calculation inside the update queue so we can use it later when we render the component. So the cycle continues, we get to the new state function, React performs the updates inside the queue, and if the action already has a cached result, it uses it and updates the state of the hook. So we have these two modes, lazy or eager. With lazy, React only performs the actions when they are needed, and with eager, they are performed immediately. And lazy is used to save redundant calculations and postpone them, and eager is used to bail out and save redundant re-renders.
And the final part is when does React decide to re-render? So when you have event handlers, for example, on click, React runs them inside something they call a batch. And inside the batch, all of the updates are queued. So in this case, we have two calls to set counter, both of them are queued. And when the function completes, the batch is over and React re-renders. So in this case, we have two updates in the queue and one re-render. And what about async event handlers? With this example, the function completes before the async operation is done. So in this case, when we get to set counter, we're already outside of the batch which means that it will trigger a re-render immediately after calling set counter. So in this case, we will have two calls to set counter and two re-renders of the component. And now, there are ways to manually invoke the batch, but we won't talk about them during this talk. So, in fact, we are done. I hope you enjoyed. I hope you learned something new and remember that you can always open the source code of React Hooks. If you find it hard, you can contact me and I'll help you. And if you have any other questions, I'll be happy to answer them in the Discord channel. And I hope you have a good conference and stay safe and I hope to see you all face to face soon. Bye bye.