When you update both changed and unchanged states in React, the Virtual DOM (VDOM) diffing algorithm (Reconciliation) ensures that only the actual differences are reflected in the real DOM.
How It Works?
Render Phase:
React creates a new Virtual DOM tree with the updated state.
It compares the new Virtual DOM with the previous Virtual DOM (diffing process).
Diffing & Optimization:
React skips unchanged states since they don’t affect the UI.
It identifies the minimum number of updates required.
Commit Phase:
Only the changed parts of the real DOM are updated efficiently.
Code Example
import React, { useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
const [name, setName] = useState("Alice");
const updateStates = () => {
setCount(1); // Changed state
setName("Alice"); // Unchanged state
};
console.log("Component Rendered"); // Observe if it re-renders
return (
<div>
<p>Count: {count}</p>
<p>Name: {name}</p>
<button onClick={updateStates}>Update State</button>
</div>
);
};
export default App;
Related Question : Force React component rerender without setState