- State/Prop Update Triggered
- When you call
setState (e.g., setCount(count+1)) or when props change from parent.
- React marks the component as “dirty” (needs re-render).
- Re-render Virtual DOM
- React calls the component function again (functional component gets executed).
- A new Virtual DOM tree is created for that component.
- Diffing Algorithm Runs
- React compares previous Virtual DOM with the new one.
- Finds what exactly changed.
- Reconciliation Process
- Based on diffing, React decides:
- Update only changed attributes/text.
- Or replace an element if type is different.
- Or reorder list items based on
key.
- Real DOM Update (Minimal Changes)
- React applies only necessary updates to the actual browser DOM.
- Browser Paints the UI
🔹 Example: State Change in Action
import React, { useState } from "react";
function StateChangeExample() {
const [count, setCount] = useState(0);
console.log("Component re-rendered!"); // Runs on every state change
return (
<div>
<h2>Count: {count}</h2>
{/* ✅ When clicked, setCount changes state */}
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default StateChangeExample;
🔹 What happens here?
- First render →
count = 0.
- When you click Increment:
setCount(count+1) triggers state change.
- Component function executes again → new Virtual DOM created (
count=1).
- React compares old vs new Virtual DOM.
- Only the text inside
<h2> changes (0 → 1).
- Real DOM updates just that text.
🔹 Key Points to Remember
- State/prop change → component re-renders (function runs again).
- But React’s diffing + reconciliation ensures only minimal updates in real DOM.
- React avoids unnecessary work to keep app fast.