
Re-rendering Isn't Rewriting the DOM: React's Render and Commit Phases
- كاتب موثّق
- React 19
محتويات المقال
memo, the render count drops, and the bug stays exactly where it was. The real cause had nothing to do with how often the page rendered, and seeing why takes the model React actually runs on.
The common misconception
innerHTML, which really did throw the old nodes away. React DevTools adds to it: turn on update highlighting and every component that rendered flashes, which looks a lot like repainting. And the myth is half true: rendering does cost something, and in a few specific cases React really does recreate DOM nodes. The mistake is treating those cases as the default.
What actually happens
Step 1: something triggers a render
Step 2: the render phase calls your functions
Step 3: the commit phase applies only the difference
import { useEffect, useRef, useState } from "react";export function LikeButton() { const [likes, setLikes] = useState(0); const noteRef = useRef<HTMLInputElement>(null); const firstNode = useRef<HTMLInputElement | null>(null); console.log("render", likes); // every click: React called LikeButton again useEffect(() => { firstNode.current ??= noteRef.current; // Runs after every commit and always logs true: the <input> is never recreated console.log("same <input> node:", noteRef.current === firstNode.current); }); return ( <div> <button onClick={() => setLikes(likes + 1)}>Like ({likes})</button> <input ref={noteRef} placeholder="Add a note" /> </div> );}render: React called LikeButton again from the top. The Effect runs after each commit and keeps logging true, because the <input> is still the node created on the first render, so your half-typed note survives. The only DOM write per click is the number inside the button.
When React really does replace DOM nodes
key: tear down and rebuild.
key |
import { useState } from "react";export function SearchPage({ items }: { items: string[] }) { const [query, setQuery] = useState(""); // Declared inside SearchPage: a brand-new component type on every render function SearchBox() { return <input value={query} onChange={(e) => setQuery(e.target.value)} />; } const visible = items.filter((item) => item.includes(query)); return ( <> <SearchBox /> <ul>{visible.map((item) => <li key={item}>{item}</li>)}</ul> </> );}import { useState } from "react";type SearchBoxProps = { query: string; onQueryChange: (query: string) => void };// Declared once at the top level: the same component type on every renderfunction SearchBox({ query, onQueryChange }: SearchBoxProps) { return <input value={query} onChange={(e) => onQueryChange(e.target.value)} />;}export function SearchPage({ items }: { items: string[] }) { const [query, setQuery] = useState(""); const visible = items.filter((item) => item.includes(query)); return ( <> <SearchBox query={query} onQueryChange={setQuery} /> <ul>{visible.map((item) => <li key={item}>{item}</li>)}</ul> </> );}query, SearchPage re-renders, and SearchBox is a new function, so for React it's a different component. React unmounts the old one, replaces its <input> with a new one, and focus is gone after a single character. memo can't fix that: the problem isn't how often SearchPage renders, it's that every render changes what sits at that position. Declared at the top level, SearchBox stays the same component and the input stays put.
Where the real cost of a re-render is
memo for that, and also say not to optimize prematurely: if a re-render causes no perceptible lag, memo is unnecessary.
How to apply it in your project
Stop treating re-renders as bugs A component rendering again after a state change is React doing its job. It's a problem only when you can see or measure it: typing lags, a list stutters, or the Profiler shows a slow interaction. Measure before you optimize Record the slow interaction with the Profiler tab of React DevTools. It shows which components rendered and how long each one took, so you fix the slow one instead of wrapping everything. Hunt identity changes when state or focus resets Look for components declared inside other components, keys created during render ( Math.random(),Date.now()) and conditions that swap the wrapper element. Move components to the top level and take keys from your data.Make render cheaper before making it rarer Keep fast-changing state, like an input's value, in the smallest component that needs it, and pass static parts as children. Addmemoonly where the Profiler shows a component that re-renders often with the same props and is expensive, or let React Compiler memoize for you.
Key takeaways
A re-render is React calling your component again to compute the UI; on its own, it changes nothing on screen. The commit phase writes only the differences to the DOM, so unchanged nodes keep their identity, focus and text. A new type or keyat the same position recreates DOM nodes and resets state, so declare components at the top level.Judge re-renders by measured cost, not by count: profile first, then make render cheaper or add memowhere it pays off.
التعليقات (0)