State Update Batching | Lecture 132 | React.JS đ„
Summary
TLDRThis video script delves into the intricacies of React's state update batching process. It explains how React optimizes performance by batching multiple setState calls into a single state update, triggering only one re-render instead of multiple. The speaker illustrates this concept through code examples, highlighting the asynchronous nature of state updates and the potential for stale state before the re-render. Additionally, the script covers React 18's improved batching capabilities, extending automatic batching to situations like timeouts and promises, and mentions rare cases where disabling batching might be necessary.
Takeaways
- đ€ React batches multiple state updates in event handlers into a single re-render for better performance.
- â Accessing the state variable immediately after calling setState will return the stale (previous) value, as the state update is asynchronous and only reflected after re-render.
- đ€ If you need to update state based on the previous state update in the same event handler, pass a callback function to setState instead of a value.
- đ React 18 introduced automatic batching for state updates triggered outside React event handlers, such as timeouts, promises, and native events.
- â ïž In rare cases where automatic batching causes issues, you can wrap the problematic state update in ReactDOM.flushSync() to exclude it from batching.
- 𧩠Batching state updates makes sense conceptually, as it represents a single new view rather than multiple partial updates.
- ⥠Avoiding unnecessary re-renders by batching state updates is a performance optimization provided by React out-of-the-box.
- đ Before React 18, state updates triggered outside React event handlers were not batched, leading to multiple re-renders.
- đ§ Understanding batching is important, especially when working with older React versions where it behaved differently.
- đ„ The video provides a detailed explanation of state update batching in React, a crucial concept for optimizing performance.
Q & A
What is state batching in React?
-State batching in React refers to the mechanism where multiple state updates within the same event handler are combined into a single re-render. Instead of triggering a re-render for each individual state update, React batches these updates together and performs only one re-render.
Why does React batch state updates?
-React batches state updates for performance optimization. If multiple state updates are related and meant to represent a new view, it would be inefficient to trigger multiple re-renders for each update. Batching ensures that only one re-render occurs, which improves the application's performance.
Can you access the updated state immediately after calling the setState function?
-No, you cannot access the updated state immediately after calling the setState function. The state update is asynchronous, and the new state value is only available after the re-render cycle has completed. Attempting to access the state variable right after calling setState will still give you the previous (stale) state value.
How can you update state based on the previous state value in the same event handler?
-To update state based on the previous state value within the same event handler, you can pass a callback function to the setState function instead of a single value. The callback function receives the previous state as an argument and returns the new state based on that value.
Did React batch state updates in all situations before React 18?
-No, before React 18, state updates were only batched in event handlers triggered by browser events (e.g., click, submit). Updates triggered outside of event handlers, such as timeouts, promises, or native event handlers, were not batched automatically.
What is the behavior of state batching in React 18 and later versions?
-In React 18 and later versions, state updates are batched automatically in all situations, including timeouts, promises, and native event handlers. This improvement enhances performance by reducing unnecessary re-renders.
Is there a way to opt-out of automatic batching in React?
-Yes, in rare cases where automatic batching might cause problems, you can opt-out by wrapping the problematic state update within the ReactDOM.flushSync function. This will exclude that specific update from being batched.
Why is it important to understand state batching in React?
-Understanding state batching is crucial because it affects the way you work with state updates and can have surprising results if not accounted for. It also helps in writing more efficient and performant React applications by avoiding unnecessary re-renders.
Can state batching lead to unexpected behavior if not handled properly?
-Yes, state batching can lead to unexpected behavior if not handled properly. For example, if you try to access the state value immediately after calling setState, you might get the previous (stale) state value instead of the updated one, which could cause bugs or unintended behaviors.
How does state batching relate to the overall render lifecycle in React?
-State batching is an important part of the render lifecycle in React. It occurs during the initial triggering phase, where React collects all state updates that need to be applied. The batched updates are then processed during the render phase, and a single re-render is triggered, followed by the commit phase.
Outlines
đ State Update Batching in React
This paragraph explains the concept of state update batching in React. It clarifies that when multiple state variables are updated within the same event handler, React batches these updates into a single state update, triggering only one re-render and commit phase. This behavior serves as a performance optimization, avoiding unnecessary re-renders. The paragraph also highlights that immediately after a state update, the state variable still holds the previous value until the re-render occurs, a concept known as 'stale state'.
đĄ Advanced Batching Scenarios and React 18
This paragraph discusses advanced scenarios where state update batching becomes relevant, such as timeouts, promises, and native DOM event handlers. Before React 18, batching only occurred in event handlers, but React 18 introduced automatic batching in these other situations for better performance. The paragraph also mentions the ReactDOM.flushSync function to exclude specific updates from batching in rare problematic cases. It concludes by emphasizing the importance of understanding batching behavior, especially when working with older React versions.
Mindmap
Keywords
đĄRender phase
đĄKey prop
đĄState updates
đĄBatching
đĄAsynchronous state updates
đĄCallback function
đĄReact 18
đĄReactDOM.flushSync
đĄPerformance optimization
đĄFiber tree
Highlights
React batches multiple setState calls into a single state update for the entire event handler, triggering only one re-render and commit phase.
Batching state updates is a performance optimization in React, as it avoids unnecessary re-renders and wasted renders.
When referencing a state variable immediately after updating it, the variable still holds the previous state value until the re-render occurs.
Updating state in React is asynchronous because the updated state is only available after the re-render, not immediately after the setState call.
To update state based on the previous state in the same event handler, use a callback function with setState instead of passing a single value.
Before React 18, automatic batching only occurred in event handlers, but not in situations like timeouts, promises, or native DOM events.
React 18 introduced automatic batching everywhere in the code, including timeouts, promises, and native DOM events.
In rare situations where automatic batching is problematic, you can use ReactDOM.flushSync to exclude a state update from batching.
Batching state updates is a performance optimization that avoids unnecessary re-renders and wasted renders.
When referencing a state variable immediately after updating it, the variable still holds the previous state value until the re-render occurs.
Updating state in React is asynchronous because the updated state is only available after the re-render, not immediately after the setState call.
To update state based on the previous state in the same event handler, use a callback function with setState instead of passing a single value.
Before React 18, automatic batching only occurred in event handlers, but not in situations like timeouts, promises, or native DOM events.
React 18 introduced automatic batching everywhere in the code, including timeouts, promises, and native DOM events.
In rare situations where automatic batching is problematic, you can use ReactDOM.flushSync to exclude a state update from batching.
Transcripts
â«So we have dived really deep
â«into some aspects of the render phase,
â«like the rules for render logic, and how the key prop works.
â«But now let's take one step back,
â«and go back to one very important aspect
â«of the first triggering phase,
â«which is the fact that state updates are batched.
â«So in that first lecture about how rendering works,
â«we had this sentence, which says
â«that renders are not triggered immediately.
â«And so in this lecture I want to focus on this part
â«which says that there is also batching
â«of multiple setState calls.
â«Now, as always, the easiest way of explaining
â«difficult concepts is by using a small code example.
â«So here we have three pieces of state,
â«defined using the useState hook,
â«and we also have a button in the user interface.
â«Then whenever there is a click on the button,
â«the event handler function named reset is called.
â«In this function, the three pieces of state,
â«answer, best, and solved,
â«are basically reverted back to their original state
â«and therefore, this function is called reset.
â«Now, actually this is the part
â«that interests us in this lecture.
â«And so let's now focus only on the event handler function.
â«Now what I want to do here is to analyze
â«how these three pieces of state
â«are actually updated behind the scenes.
â«So we might think that, as React sees
â«the set answer function call,
â«it would update the state to the empty string as requested,
â«and then trigger a re-render, and the commit phase,
â«then it would move on to the next line,
â«and to the same thing again,
â«and finally do the entire thing
â«one more time for the third state update.
â«So intuitively, we would think that,
â«if there are three state variables
â«being updated in this event handler,
â«then React would re-render three times, right?
â«However, this is actually not how it works.
â«So this is not how React updates multiple pieces of state
â«in the same event handler function.
â«Instead, these state updates will actually get batched
â«into just one state update for the entire event handler.
â«So updating multiple pieces of state
â«won't immediately cause a re-render for each update.
â«Instead, all pieces of state inside the event handler
â«are updated in one go.
â«So they are batched, and only then
â«will React trigger one single render and commit.
â«And conceptually, it makes sense that React works this way,
â«because if we're updating these pieces of state together,
â«it probably means that they should just represent
â«one new view, and therefore,
â«React only updates the screen once.
â«So if these date updates belong together,
â«it really wouldn't make much sense
â«to update the screen three times.
â«Doing so would also create two wasted renders,
â«because we're not interested in the first two renders,
â«only the final one, which already contains
â«all the three state updates.
â«Therefore, the fact that React
â«automatically batches state updates in this way
â«is yet another performance optimization
â«that React gives us out of the box.
â«Now, batching state updates is extremely useful,
â«but it can also have surprising results.
â«So let's turn our attention to this line of code now,
â«where we reference the answer state variable
â«right after updating it.
â«So what do you think will be the value
â«of this variable at this point?
â«Well, let's try to think about this.
â«So remember, that component state is stored
â«in the fiber tree during the render phase.
â«Now, at this point in the code,
â«the render phase has not happened yet.
â«So React is still reading the function line by line
â«to figure out what state needs to be updated,
â«but it hasn't actually updated the state yet,
â«and it also hasn't re-rendered yet.
â«That's the whole point of batching state updates
â«in the first place, right?
â«So what this means is that, at this point of the code,
â«the answer variable will still hold the current state.
â«So the state before the update,
â«even though we already told React to update it.
â«So at this point we say that our state is stale,
â«meaning that the state is no longer fresh and updated,
â«because in fact, a state update will only be reflected
â«in the state variable after the re-render.
â«And so for this reason, we say that updating state in React
â«is asynchronous, and again, it is asynchronous
â«because React does not give us the updated state variable
â«immediately after the set answer call,
â«but only after the re-render has happened.
â«Now, the same thing is also true
â«whenever there is only one piece of state being updated.
â«So no matter how many state variables are being updated,
â«the updated state is only available
â«after the re-render, not immediately.
â«Now, sometimes we actually do need the new value
â«immediately after updating it, and in the case,
â«that we need the new value
â«in order to update the same state again.
â«Or in other words, if we need to update state based
â«on a previous state update in the same event handler,
â«we can pass a callback function into the set state function
â«instead of a single value.
â«And we have actually done this in practice
â«all the time, right?
â«Now, so far, we have only talked about batching
â«in event handler functions, like our reset function.
â«That's because before React 18,
â«React only did automatic batching in event handlers,
â«but not in situations that happen
â«after a browser event has already happened.
â«However, there are certain very important situations
â«in which we do need to update state,
â«long after a browser event, like a click, has happened.
â«Examples of that are timeouts and promises,
â«for instance, we might want to run our reset function
â«only a second after a click event,
â«or we might want to run it after some data has been fetched.
â«So it would be nice to also have automatic batching
â«in those situations to improve performance, right?
â«Well, that's actually one of the important features
â«that React 18 gave us.
â«So before React 18, if this reset function
â«was called by a timeout, or by a promise,
â«state updates inside the function would not be batched.
â«Instead, in these situations, React would actually
â«update the state variables one by one, and therefore,
â«in this case, render three times.
â«Now another case is handling native events using DOM methods
â«such as addEventListener, where state updates
â«also used to not be batched, but now they are.
â«So again, if you're using the latest React version,
â«you will now get automatic batching all the time,
â«everywhere in your code.
â«And if, for some reason, you are working
â«with an older version of React, maybe at your work,
â«it's important that you know that batching used to work
â«in a different way before version 18.
â«Now, there are also some extremely rare situations
â«in which automatic batching can be problematic.
â«So if you ever find yourself in a situation like that,
â«you can just wrap the problematic state update
â«in a ReactDOM.flushSync function,
â«and React will then exclude that update from batching.
â«But you will most likely never need this.
â«I'm just mentioning this here,
â«so that you know that it exists.
â«Now, okay, and that's it about state update batching.
â«It turned out to be a bit longer than I thought,
â«but as always, there is just
â«so much interesting stuff to learn,
â«and so I hope that you don't mind at all.
â«But in any case, let's quickly go to the next video,
â«so I can show you some of this in practice.
Weitere Àhnliche Videos ansehen
State Update Batching in Practice | Lecture 133 | React.JS đ„
1 month of content in 1 hour | Updated guide to content batching & planning + free content calendar!
What are React updater functions? đ
Introduction to Redux | Lecture 257 | React.JS đ„
How NOT to Fetch Data in React | Lecture 139 | React.JS đ„
Understanding memo | Lecture 242 | React.JS đ„
5.0 / 5 (0 votes)