什麼 React 不直接操作 DOM?
既然瀏覽器本來就能用 document.querySelector()
、innerHTML
來更新畫面,為什麼還要搞一個「Virtual DOM」?
Virtual DOM(虛擬 DOM)是 React 用來更新 UI 的一種策略。
它並不是取代真實 DOM,而是存在 記憶體中的 JavaScript 物件樹,用來模擬真實 DOM 的結構。
當 state 或 props 改變時:
因為 直接操作 DOM 很昂貴:
Virtual DOM 的解法是:
const el = document.createElement("div");
el.textContent = "Hello";
document.body.appendChild(el);
function App({ name }) {
return <div>Hello {name}</div>;
}
❌ 「Virtual DOM 永遠比直接操作 DOM 快」
UI = f(state, props)
。判斷以下操作會觸發什麼:
Virtual DOM is basically a lightweight copy of the real DOM kept in memory.
Whenever state or props change, React builds a new one, compares it with the old one, and figures out what’s different.
Then it updates only those parts in the real DOM instead of re-rendering everything.
This way we avoid too many reflows and repaints, and the UI feels much faster.
Virtual DOM 你可以把它想像成真實 DOM 的「記憶體副本」。
每次 state 或 props 改變,React 會先在記憶體裡做一份新的 Virtual DOM,然後跟舊的比,看看哪裡不同。
最後它只動真實 DOM 裡需要更新的部分,而不是整棵都重畫。
這樣就可以避免過多的 reflow 跟 repaint,效能就順很多。