JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
senior
internals

How does React's reconciliation algorithm work?

reconciliation
virtual-dom
diffing
fiber
performance
internals
Quick Answer

Reconciliation is React's diffing algorithm that compares the new virtual DOM tree with the previous one to determine minimal DOM updates. It uses heuristics: different element types trigger full subtree replacement, keys identify items in lists, and same-type elements update attributes.

Detailed Explanation

What is Reconciliation:

  • Process of comparing two virtual DOM trees
  • Determines what changed and needs updating
  • Aims to minimize actual DOM operations
  • Uses heuristics for O(n) performance vs O(n³) naive diff

Key Heuristics:

  1. Different element types:

    • Old tree is torn down completely
    • New tree is built from scratch
    • All child components unmount/remount
  2. Same element type:

    • Keeps same DOM node
    • Updates changed attributes only
    • Recursively reconciles children
  3. Keys for lists:

    • Identify items across renders
    • Enable efficient reordering
    • Prevent unnecessary unmount/remount

Fiber Architecture:

  • Incremental rendering
  • Can pause, abort, or reuse work
  • Assigns priority to different update types
  • Enables concurrent features

Code Examples

Different element types
// BEFORE
<div>
  <Counter />
</div>

// AFTER: Different root element type
<span>
  <Counter />
</span>

// React will:
// 1. Unmount old <div> and <Counter>
// 2. Counter's componentWillUnmount / useEffect cleanup runs
// 3. Mount new <span> and fresh <Counter>
// 4. All Counter state is LOST!

// Same element type - just updates attributes
<div className="before" title="old" />
<div className="after" title="new" />
// React updates className and title on same DOM node

// Same component type - instance is kept
<Counter count={1} />
<Counter count={2} />
// Same Counter instance, state preserved, just re-renders

Resources

React Docs - Preserving and Resetting State

docs

React Fiber Architecture

article

Related Questions

Explain React.memo, useMemo, and useCallback. When should each be used?

senior
performance

What are React's concurrent features and how do Suspense and transitions work?

senior
concurrent
Previous
Explain React.memo, useMemo, and useCallback. When should each be used?
Next
What are React's concurrent features and how do Suspense and transitions work?