الانتقال إلى المحتوى
FrontendReact· 8 دقائق للقراءة

Re-rendering Isn't Rewriting the DOM: React's Render and Commit Phases

React calls your component again, compares the result and touches only the DOM nodes that changed.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • React 19
محتويات المقال

A bug report lands on Monday morning: "The search box loses focus after every letter." The team's first theory sounds reasonable: the page re-renders on every keystroke, so React must be rebuilding the input each time. Someone wraps half the page in 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

The belief goes like this: every time a component re-renders, React rebuilds its part of the DOM, so every re-render is expensive, and a React developer's main job is to prevent them.

It's an easy belief to pick up. In the jQuery days, re-rendering a widget often meant replacing its 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

React's docs split every screen update into three steps: something triggers a render, React renders your components, and React commits the result to the DOM. Only the last step touches the page.

Step 1: something triggers a render

The docs name two triggers: the initial render, and a state update in the component or in one of its ancestors. A parent re-rendering is enough; the child's props don't have to change. Context changes cause renders too, and the next article in this path covers every trigger.

Step 2: the render phase calls your functions

The is React calling your components: the one whose state changed, then every component it returns, recursively. The result is a fresh description of the UI made of plain JavaScript objects, not DOM nodes. React compares it with the previous one, position by position, to find what is different; this comparison is usually called . Nothing on screen has changed yet.

Step 3: the commit phase applies only the difference

In the , React applies the minimal set of DOM operations that makes the page match the new output. On the first render, that means inserting every node. On a re-render, a node that didn't change is left alone, with its typed text and focus. If the output is identical, the commit doesn't touch the DOM at all. Then the browser paints, which React's docs deliberately call painting, not rendering, to avoid this exact confusion.

You can watch it happen. Click the button a few times and type in the input between clicks:

TSX LikeButton.tsx
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>  );}

Every click logs 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

React matches the old and new output by position in the tree and checks the type at each position. Same type: keep the node, or the component and its state, and update what changed. Different type or different key: tear down and rebuild.

Between two renders, at the same positionWhat the commit doesWhat survives
Same element, same props and textNothingEverything
Same element, a changed attribute or textUpdates just that attribute or textThe DOM node, focus and state
A different element type or componentRemoves the old subtree and creates new nodesNothing
The same component with a different keyRecreates the component and its DOMNothing

That's the bug from the opening. A component declared inside another component is a brand-new function on every render, so React sees a different component type at that position each time:

TSX SearchPage.tsx
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>    </>  );}

In the first version, each keystroke updates 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

A re-render does cost something: React runs your component and everything below it, then compares the results. For most components that's a few function calls and small objects. It gets noticeable when render does heavy work, like filtering thousands of rows on every keystroke, or when a component near the top re-renders a large subtree very often. React's docs offer opt-in tools like 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

  1. Stop treating re-renders as bugsA 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.
  2. Measure before you optimizeRecord 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.
  3. Hunt identity changes when state or focus resetsLook 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.
  4. Make render cheaper before making it rarerKeep fast-changing state, like an input's value, in the smallest component that needs it, and pass static parts as children. Add memo only 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 key at 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 memo where it pays off.

📚 المصادر

  1. Render and Commit — React
  2. Preserving and Resetting State — React
  3. memo — React API Reference
  4. StrictMode — React API Reference
  5. useMemo — React API Reference

التعليقات (0)