Sub topic 2
How React Batches State Updates
Assume you know JavaScript functions, objects, and arrays, basic React components and JSX, useState, and the browser DOM.
How React batches state updates
React usually batches state updates. Batching means React groups several updates from one event into one render and commit. This avoids repeated work.
Each render sees a fixed snapshot of state. Calling a setter does not immediately change the variable in the current render. When a later update depends on an earlier update, use an updater function.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function addTwo() {
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<>
<p>Count: {count}</p>
<button onClick={addTwo}>Add two</button>
</>
);
}With a modern React root, React also batches updates from many asynchronous callbacks, such as timers and promise handlers. The exact timing depends on how the update is scheduled.
Reconciliation: how React compares two trees
After a state update, React calls components to produce a new element tree. Reconciliation is React’s process for comparing that tree with the previous one. React then commits the required changes to the DOM.
React does not rebuild every DOM node blindly. It uses element type, position, and keys to decide which existing instances can be reused.
Type and position decide whether state is kept or reset
State belongs to a component’s position in the rendered tree. If the same component type remains at that position, React normally preserves its state. If the type changes, React removes the old subtree and creates a new one.
A key can deliberately change identity and reset state:
function Profile({ userId }) {
return <EditForm key={userId} userId={userId} />;
}When userId changes, the new key tells React to create a fresh EditForm.
Keys and stable identity in lists
A key identifies an item among its siblings. Use a stable identifier from the data, such as a database ID. Do not use an array index when items can be inserted, removed, or reordered.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}Exercise
Why can using an array index as a key move one todo item’s state to another item?
Show answer
Reordering changes which data occupies that index, so React may reuse the old component instance for different data.