The diffing algorithm is React’s way of figuring out what has changed in the Virtual DOM and updating only those parts in the Real DOM instead of re-rendering the entire UI.
- Why needed?
- Updating the whole DOM is slow.
- React maintains a Virtual DOM (lightweight copy of Real DOM).
- On every state/prop change → React compares (diffs) the new Virtual DOM with the old one.
- Only the changed nodes are updated in the Real DOM → making React fast.
- How it works (simplified rules):
-
Different element type → replace entire node
<div /> → changes to <span /> // React removes <div> and creates a new <span> -
Same type element → update only changed attributes
<button className="red" /> → <button className="blue" /> // Only "className" is updated, not entire button - Lists → key property used for efficient updates
- React uses
keyto match old & new list items. - Without
key, React may re-render unnecessarily.
- React uses
-
🔹 Example: Diffing in Action
import React, { useState } from "react";
function DiffingExample() {
const [isRed, setIsRed] = useState(true);
const [items, setItems] = useState(["Apple", "Banana", "Orange"]);
return (
<div>
{/* ✅ Diffing updates only style, not whole button */}
<button
style={{ color: isRed ? "red" : "blue" }}
onClick={() => setIsRed(!isRed)}
>
Change Color
</button>
{/* ✅ Keys help React match items efficiently */}
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li> {/* key is important */}
))}
</ul>
<button onClick={() => setItems([...items, "Mango"])}>
Add Mango
</button>
</div>
);
}
export default DiffingExample;
🔹 Key Takeaways
- Diffing algorithm = React’s way to update only necessary parts of DOM.
- Improves performance by avoiding full re-renders.
keyin lists is critical for correct & efficient diffing.