Skip to content
FrontDepth, Home

React & Rendering

Reconciliation and re-renders

What makes a React component render, how React compares element trees and decides what to keep, and how to stop needless re-renders — from keys and state position to memo, context, batching and the React Compiler.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What a render is and what triggers it

In React, rendering means React calling your component — running the function to find out what it should show. It is not the same as changing the page: the is touched only later, and only where something differs.

A component renders for one of these reasons:

  1. The initial render, started by createRoot(container).render(<App />).
  2. Its own state changed — a set function from useState or dispatch from useReducer queued a render.
  3. Its parent rendered. By default, when a component renders, React renders every component it returns, all the way down — whether or not their props changed.
  4. A context it reads changed: every component that reads the context renders when the nearest provider gets a different value.

"Its props changed" is not on the list: props only change because the parent rendered, which is reason 3.

JSX
import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  console.log("render App", count);
  return (
    <>
      <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
      <Hint />
    </>
  );
}

function Hint() {
  console.log("render Hint");
  return <p>Press the button</p>;
}

Each click logs render App with the new count and render Hint. Hint has no props and shows the same text, yet React calls it again because its parent rendered. Then React compares the result with the previous one: the button's text changed, so React updates that one text node; the <p> is identical, so its DOM node is left alone.

Why this is fine — usually

Calling a small function is cheap; DOM work, layout and paint are what cost. A re-render that produces the same output does no DOM work at all. Re-renders become a problem when a component high in the tree updates often (on every keystroke, scroll or timer tick) and the tree below it is large or slow to render. That is what the rest of this topic is about.

Two habits to start with

  • Rendering must be pure: the same props, state and context should produce the same output, without changing outside variables or the DOM. In development, Strict Mode calls components twice to surface impure ones, so a console.log in render may appear twice.
  • Find out before you fix. The React DevTools Profiler records which components rendered and why, and the DevTools setting "Highlight updates when components render" flashes every component that renders.
JuniorConcept

Render and commit: elements are descriptions

Every screen update goes through three steps, as react.dev describes them: trigger (the initial render or a state update), render (React calls your components) and commit (React changes the DOM). After the commit, the browser paints.

Elements: plain objects that describe the UI

JSX compiles to function calls that return elements — small objects that say what to show, not instructions:

JSX
const heading = <h1 className="title">Hello</h1>;
console.log(heading.type, heading.props);
// h1 { className: 'title', children: 'Hello' }

const profile = <Profile userId={7} />;
console.log(profile.type === Profile, profile.props);
// true { userId: 7 }

An element has a type (a tag name like "h1" or your component function), props and a key. Creating <Profile userId={7} /> does not call Profile; React calls it later, during render, when it meets that element in the tree.

Render: build the next tree

React calls the component that needs to update, takes the elements it returns, calls the components inside them, and so on. It compares the new elements with what it rendered last time — this comparison is reconciliation — and works out the changes: which DOM nodes to create, which attributes or text to update and which nodes to remove. React keeps its own tree of fibers (one per component instance or host element) to remember what was rendered and to store each component's state and hooks.

During render nothing visible happens yet. In React 18 and later, React may pause or throw away a render that is not urgent (a transition) and start again; that is another reason render must be pure.

Commit: apply the minimal changes

In the commit, React applies the list of changes to the DOM, attaches refs and runs layout effects; useEffect effects run afterwards, usually once the browser has painted. On the first render it inserts the whole tree with appendChild(). On later renders, React only changes the DOM nodes that differ: react.dev's example is a clock that updates an <h1> every second while an <input> next to it keeps what the user typed, because React never replaced the input.

The mental model

  • setState → React schedules a render of that component.
  • Render → your functions run and return elements; React diffs them against the previous tree.
  • Commit → only the differences reach the DOM; then the browser does layout and .

The platform's Mini React build project has you write this pipeline yourself: createElement, rendering to the DOM, reconciliation and keys, function components, useState, batching and useEffect.

MiddleWeb platform

How React compares trees: type, position, key

Comparing two arbitrary trees optimally is far too slow — general algorithms are O(n³). React instead uses a heuristic that is O(n), built on two assumptions the old React docs spelled out: elements of different types produce different trees, and keys tell React which children stay the same between renders.

Same type at the same position: keep and update

If the element at a position has the same type as last time, React keeps the DOM node or component instance and only updates what changed — attributes, text, props. A component keeps its state.

JSX
function Scoreboard({ isFancy, isPaused }) {
  if (isPaused) return <p>See you later!</p>;
  return isFancy ? <Counter fancy /> : <Counter />;
}

Switching isFancy keeps the Counter's count: in both branches it is a Counter in the same place. React does not look at the JSX lines; what matters is the position in the rendered tree, so two <Counter /> tags in different branches of an if are "the same counter" if they end up in the same slot.

Different type: remount the whole subtree

When isPaused turns true, the slot holds a <p> instead of a Counter. React unmounts the Counter (its effects are cleaned up, its state is gone), removes its DOM, and builds the <p> from scratch. Switching back mounts a fresh Counter at 0. The same happens one level up: wrapping the same Counter in a <section> in one render and a <div> in the next resets everything inside, because the parent's type changed.

The bug this explains: components defined inside components

JSX
function SignupForm() {
  const [email, setEmail] = useState("");

  function EmailField() {
    return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
  }

  return <EmailField />;
}

Every render of SignupForm creates a new EmailField function, so React sees a different type at the same position and remounts the input on every keystroke. The input loses focus after each letter. Declare components at the top level of the module, never inside another component.

Resetting state on purpose with key

A key becomes part of the position. Rendering

JSX
<Chat key={contact.id} contact={contact} />

gives each contact its own Chat: switching contacts unmounts the old one and mounts a new one, so a half-typed message is not sent to the wrong person. Keys only have to be unique among siblings, not globally.

MiddlePitfalls

Keys in lists and the bugs of index keys

For a list, React has to match the new children with the old ones. Without keys it can only match by position: the first child with the first child, and so on. Appending at the end is fine, but inserting at the start makes every position hold a different item, and React updates every child. Keys let React match children by identity instead, so a moved, inserted or removed item keeps its own DOM node and state.

Index keys move state to the wrong item

JSX
function ShoppingList({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>
          {item.name} <input placeholder="Note" />
        </li>
      ))}
    </ul>
  );
}

The user types "2 l" into the note next to Milk. Then an item is added at the top. With key={index}, Eggs gets key 0 — the key that Milk had — so React reuses Milk's <li> and its <input> for Eggs: the note "2 l" is now next to the wrong item, and every other row shifts too. The same happens after sorting or deleting. With key={item.id}, React sees a new key at the front, creates one new row, and moves nothing else.

An index key is only safe when the list never reorders, never inserts or removes in the middle, and its items have no state of their own (including uncontrolled inputs and focus). React uses the index when you pass no key at all, and warns about the missing key.

Other key mistakes

  • Keys generated during render — key={Math.random()} or crypto.randomUUID() in map. The keys never match between renders, so React recreates every row and its DOM on each render: slow, and input in the rows is lost. Create ids when the data is created, not when it is rendered.
  • Duplicate keys among siblings: React warns, and items can be duplicated or dropped on update.
  • Expecting key as a prop. A component does not receive key; pass the id separately: <Row key={id} id={id} />.
  • Keys on the wrong element: the key belongs on the outermost element returned from map, not on something inside it.

Keys are also a tool

Because a changed key means "a different item", you can reset a subtree deliberately: <Form key={user.id} /> starts a fresh form for each user, with no effect that "syncs" state.

MiddleExample

Re-render cascades and how to stop them without memo

A state update re-renders the component that owns the state and everything below it. If that state lives high in the tree and changes often, a cascade of renders follows. Before reaching for memo, fix the structure — react.dev recommends these first.

Move state down

Say a photo page keeps the text of its comment box in its own state, next to a grid of 200 photos: every keystroke re-renders the page and the whole grid. Only the text area needs the text, so give it a component of its own:

JSX
function CommentBox() {
  const [comment, setComment] = useState("");
  return <textarea value={comment} onChange={(e) => setComment(e.target.value)} />;
}

function PhotoPage({ photos }) {
  return (
    <>
      <PhotoGrid photos={photos} />
      <CommentBox />
    </>
  );
}

Now typing re-renders CommentBox alone. PhotoGrid is a sibling, not a child, of the state owner.

Lift content up: pass JSX as children

Sometimes the state has to wrap the expensive part — a reading-progress bar around an article, a modal around a form:

JSX
function ReadingProgress({ children }) {
  const [progress, setProgress] = useState(0);
  return (
    <div className="reader" onScroll={(e) => setProgress(scrolledShare(e.currentTarget))}>
      <ProgressBar value={progress} />
      {children}
    </div>
  );
}

function ArticlePage({ article }) {
  return (
    <ReadingProgress>
      <Article article={article} />
    </ReadingProgress>
  );
}

Scrolling updates progress and re-renders ReadingProgress, but <Article /> was created by ArticlePage, which did not render. children is the same element object as last time, so React skips the Article subtree. The component owns the state; its parent owns the content.

Keep expensive work out of unrelated renders

A component that sorts or filters hundreds of items in its body repeats that work on every state change — also on changes that have nothing to do with the list, like a toggle or a text field next to it. Move that unrelated state into a component of its own (state down again), or cache the result: useMemo(() => sortProducts(products, sortKey), [products, sortKey]) sorts again only when its inputs change.

Checklist

  1. Which state changes most often, and which component owns it?
  2. Can that state live lower, next to the only part that reads it?
  3. Can the expensive part be passed in as children or another JSX prop?
  4. Is there expensive computation in render that does not depend on what changed?

Only when the answers are "no" — the state really is needed high up, and the children are expensive — does memoization become the tool.

SeniorFramework

memo, useMemo, useCallback — and when they are wasted

in React means reusing a previous result when the inputs are the same.

  • memo(Component) skips re-rendering when every prop is equal to last time, compared with Object.is.
  • useMemo(fn, deps) caches a computed value between renders until a dependency changes.
  • useCallback(fn, deps) caches a function; it is useMemo(() => fn, deps).
JSX
import { memo, useCallback, useMemo, useState } from "react";

const ProductRow = memo(function ProductRow({ product, onSelect }) {
  return <li onClick={() => onSelect(product.id)}>{product.name}</li>;
});

function ProductList({ products, query }) {
  const [selectedId, setSelectedId] = useState(null);
  const visible = useMemo(
    () => products.filter((product) => product.name.includes(query)),
    [products, query],
  );
  const handleSelect = useCallback((id) => setSelectedId(id), []);

  return (
    <>
      <p>Selected: {selectedId ?? "none"}</p>
      <ul>
        {visible.map((product) => (
          <ProductRow key={product.id} product={product} onSelect={handleSelect} />
        ))}
      </ul>
    </>
  );
}

Selecting a product re-renders ProductList, but no row renders: each row's product and onSelect are the same as before, and the filter does not run again because products and query did not change. Without useCallback, onSelect would be a new function on every render and every row would render anyway.

When memoization is wasted

  • Props that are new on every render — an inline style={{ … }}, onClick={() => …}, JSX children: memo compares, finds a difference and renders anyway.
  • Cheap components: comparing the props can cost as much as rendering.
  • Renders from the component's own state or context: memo only looks at props.
  • Fast calculations: react.dev suggests measuring with console.time and memoizing from about 1 ms.
  • Correctness: useMemo is a performance hint, not a guarantee, and React may drop the cache. And a wrong dependency array, such as useCallback(fn, []), freezes the first render's values — a .

React Compiler

React Compiler 1.0 is stable since October 7, 2025: a build-time tool (babel-plugin-react-compiler) that follows the Rules of React and memoizes components and hooks automatically, even after an early return, where manual hooks cannot be called. It supports React 17 and later (17 and 18 need react-compiler-runtime); it memoizes only inside components and hooks, and does not share caches between components.

With the compiler, memo is usually unnecessary. In new code, rely on it and keep useMemo/useCallback as escape hatches, for example for a value used as an effect dependency. In existing code, react.dev advises leaving manual memoization in place or testing carefully before removing it, since that can change the compiled output.

SeniorFramework

Context: why one change re-renders every consumer

Context passes a value to every component below a provider without props. The performance rule is short: when a provider receives a different value (by Object.is), every component that reads that context re-renders, starting from the provider. memo does not stop it — it only compares props.

One big context

Say a dashboard shares everything through one value: the locale, the list of notifications (new ones arrive every few seconds) and a function to dismiss one:

JSX
function AppProvider({ locale, children }) {
  const [notifications, setNotifications] = useState([]);
  const dismiss = (id) => setNotifications((list) => list.filter((n) => n.id !== id));

  return (
    <AppContext value={{ locale, notifications, dismiss }}>
      {children}
    </AppContext>
  );
}
  1. The value is a new object on every render, so every consumer re-renders whenever the provider renders.
  2. Even with useMemo around it, every new notification changes the value, and all consumers re-render — including dozens of widgets that only need the locale to format their numbers.

Split by what changes together

JSX
function AppProvider({ locale, children }) {
  const [notifications, setNotifications] = useState([]);
  const dismiss = useCallback(
    (id) => setNotifications((list) => list.filter((n) => n.id !== id)),
    [],
  );

  return (
    <LocaleContext value={locale}>
      <NotificationActionsContext value={dismiss}>
        <NotificationsContext value={notifications}>{children}</NotificationsContext>
      </NotificationActionsContext>
    </LocaleContext>
  );
}

function RevenueWidget({ total }) {
  const locale = useContext(LocaleContext);
  return <p>{new Intl.NumberFormat(locale).format(total)}</p>;
}
  • Each provider gets a value that is stable between renders: a primitive, a state value, or a function from useCallback.
  • Consumers read only what they need. RevenueWidget reads LocaleContext, which changes only when the language does, so a new notification no longer re-renders the widgets.
  • State that only one component needs (a draft in a text field) does not belong in context at all: keep it in that component.

react.dev's pattern of one context for state and one for dispatch is a good start; split further when parts of the state change at different rates.

Selecting less

Context has no built-in selector: a consumer re-renders when the value changes, even if it uses one field. When many components read different slices of fast-changing data, use a store with selectors: stores read through useSyncExternalStore (Zustand and Redux work this way) re-render a component only when its selected slice changes.

Since React 19 a context is rendered directly as its provider (<LocaleContext value={locale}>), as in the code above.

SeniorWeb platform

Batching and what happens inside setState

A set function does not change the variable you are holding — it queues an update and asks React to render again. The current render's count stays the same until the next render; react.dev calls state a snapshot.

Automatic batching

React waits until all code in the event handler has run, then renders once for all the updates — this is . Since React 18 (with createRoot), updates are batched everywhere: in event handlers, timeouts, promise callbacks and native event listeners. Before React 18, only updates inside React event handlers were batched. React does not batch across separate intentional events: each click is handled on its own.

The update queue

JSX
function handleClick() {
  setNumber(number + 5);
  setNumber((n) => n + 1);
  console.log(number);
}

number is 0 in this render. The queue holds "replace with 5", then n => n + 1. The handler logs 0, and on the next render React processes the queue in order: 5, then 6. A plain value replaces whatever was queued before it; an updater function receives the result of the previous update. That is why setCount(c => c + 1) three times adds 3, while setCount(count + 1) three times adds 1.

If the new value is the same as the current state (Object.is), React skips re-rendering the component and its children. Sometimes it still has to call the component once before it can skip the children; that is expected.

Opting out: flushSync

Rarely you need the DOM updated right away, for example to scroll to a new item:

JSX
import { flushSync } from "react-dom";

function handleAdd(todo) {
  flushSync(() => {
    setTodos((list) => [...list, todo]);
  });
  listRef.current.lastChild.scrollIntoView();
}

flushSync renders and commits the update inside the callback synchronously. It is expensive and blocks the main thread — use it only for cases like this.

Inside React

The platform's source tour "React: how useState works" (react-use-state, React v19.3.0) follows this through React's code: useState asks the current dispatcher, which the renderer switches between mount and update; each component's hooks are a linked list on its fiber, found by call order (the reason for the Rules of Hooks); a set call creates an update, may bail out early with Object.is, appends it to the hook's update queue, marks the fiber and its parents with a priority lane, and schedules one render for however many updates came in. The next render replays the queue in order. A minimal version of the same idea collects updates and flushes them together in one .

SeniorInterview tips

Interview tips

A 30-second answer. "Rendering is React calling your components to get elements — descriptions of the UI. A component renders on mount, when its state changes, when its parent renders, or when a context it reads changes. React diffs the new elements against the previous tree — same type at the same position keeps state, a different type remounts, keys identify list items — and commits only the differences to the DOM."

Questions you are likely to get

  • Does a re-render update the DOM? No: rendering calls components; only differences are committed.
  • Why do keys matter? Why not the index? Matching by identity vs position; show the input moving to the wrong row.
  • Why did this state reset? A different type at the same position, a changed wrapper, a component defined inside another, or a changed key.
  • This page lags while typing — what do you do? Profile first. Then move state down, pass content as children, memoize with stable props, split context, and consider the React Compiler. Mention the platform's challenges as practice: perf-typing-lag, perf-slow-filter, perf-context-storm.
  • How many renders does this handler cause? Batching: one per event, in timeouts and promises too since React 18; updater functions vs plain values.

Mistakes that cost points

  • Saying "React re-renders a component when its props change". It re-renders when the parent renders; changed props are a consequence.
  • Saying "re-rendering means re-creating the DOM".
  • Wrapping everything in memo/useMemo "to be safe", or believing memo blocks context updates.
  • Using Math.random() or the index as a key for a list that changes.
  • Saying React diffs "the virtual DOM against the real DOM". It compares the new elements with its previous tree (fibers), not with the live DOM.

Senior signal

Explain trade-offs with numbers from a profile, know why the structure fixes (state down, children) come before memoization, how the React Compiler changes that advice, and how state lives on fibers as a queue of updates.

JuniorReview checklist

What to check when reviewing keys and re-renders

Use this list when you review React components you did not write: a teammate's, a library's or an AI assistant's. Without it, state that resets or lands on the wrong row, lost focus and needless re-renders slip through.

  • Are list keys taken from the data (item.id), not the index or Math.random()? Index keys move typed text and focus to the wrong row after an insert or a sort; random keys recreate every row on each render. Type into a row, then add an item at the top: the text must stay with its item.
  • Is a component declared inside another component? Each render makes a new function, a new type for React, so it remounts: state is lost and an input loses focus after every letter.
  • Does a component with state keep its type and position when the JSX changes? A different wrapper (<div> instead of <section>) or element in that slot unmounts it with its state; a wanted reset should use a key, as in <Form key={user.id} />, not an Effect that clears state.
  • Does state that changes often sit above a large subtree? Every update re-renders everything below its owner: can the state move down, or the expensive part come in as children? The React DevTools Profiler shows what rendered and why.
  • Are the values that memo and context compare stable? memo checks each prop with Object.is, so an inline object, function or JSX children makes it render anyway; a provider value={{ … }} built during render re-renders every consumer each time the provider renders.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Guided tours through the source of real libraries that rely on it.