BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE React Interview Notes - Virtual DOM and React Fiber Analysis

Deep dive into React's Virtual DOM mechanism and Fiber architecture, including working principles, performance optimization, the role of keys, and common interview questions analysis.

影片縮圖

Lazy to read articles? Then watch videos!

Virtual DOM: Principles and Advantages

What is Virtual DOM?

Virtual DOM is a core concept in React, representing a lightweight, pure JavaScript representation of the real DOM. Essentially, it's a JavaScript object tree that describes the DOM structure and its properties.

When application state changes, React doesn't directly manipulate the real DOM. Instead, it first updates this virtual representation in memory, then efficiently calculates the minimal updates needed for the actual DOM through a process called 'Reconciliation'.

Virtual DOM Representation

// A simplified example of a Virtual DOM node
const virtualDOMNode = {
  type: 'div',
  props: {
    className: 'container',
    children: [
      {
        type: 'h1',
        props: {
          children: 'Title'
        }
      },
      {
        type: 'p',
        props: {
          children: 'Paragraph content'
        }
      }
    ]
  }
};

// The actual Virtual DOM structure in React is more complex

Corresponding HTML

<!-- Actual HTML corresponding to the Virtual DOM above -->
<div class="container">
  <h1>Title</h1>
  <p>Paragraph content</p>
</div>

Why do we need Virtual DOM?

Manipulating the real DOM is expensive. Each direct DOM modification causes the browser to perform reflow and repaint, which can create performance bottlenecks in modern applications that require frequent UI updates.

DOM Operation Performance Issues

  • 1. Reflow and repaint consume significant computational resources
  • 2. Frequent DOM operations lead to page performance degradation
  • 3. Direct DOM modifications are difficult to track
  • 4. Code that directly manipulates DOM is difficult to maintain and debug

Advantages of Virtual DOM

  • 1. Combines multiple DOM operations into a single update
  • 2. Efficiently calculates minimal necessary DOM changes
  • 3. Reduces the number of reflows and repaints
  • 4. Provides a declarative UI programming model
  • 5. Makes cross-platform development easier

Virtual DOM Workflow

The complete process from JSX to page rendering in React is as follows:

JSX → Virtual DOM Tree
Fiber Processing & Diffing
Reconciliation (Interruptible)
Commit (Non-interruptible)
DOM Update
Execute useLayoutEffect
Browser Paint
useEffect Execution

Simple Explanation:

  • 1. Virtual DOM: Like a sketch pad, drawing drafts before painting on the wall
  • 2. Fiber: Breaking big tasks into small pieces, can pause to handle more important things
  • 3. Diffing: Comparing old and new sketches, only marking parts that need changes
  • 4. Reconciliation: Planning phase, deciding what needs to be updated
  • 5. Commit: Execution phase, actually applying changes to DOM
  • 6. useLayoutEffect: Executes before screen display, can measure and adjust DOM
  • 7. useEffect: Executes after screen display, suitable for non-urgent tasks

Virtual DOM Diffing Algorithm

The Diffing algorithm is key to Virtual DOM's efficiency. React implements an O(n) algorithm based on two assumptions:

1. Different types of elements produce different trees

If an element changes from div to span, React will completely rebuild the tree rather than trying to match.

2. Use key to identify stable elements

Adding a key helps React identify which elements are new, moved, or deleted.

Why do we need keys?

// ❌ Bad: Using index as key
<ul>
  <li>Home</li>
  <li>About</li>
</ul>

// ✅ Good: Using unique ID
<ul>
  <li key="home">Home</li>
  <li key="about">About</li>
</ul>

Performance Tip: Virtual DOM is usually more efficient than direct DOM manipulation, but not always the fastest in all scenarios. React's advantage lies in providing a good development experience and reasonable performance balance.

React Fiber: Modern Reconciliation Engine

What is React Fiber?

React Fiber is a reconciliation engine introduced in React 16, rewriting React's core algorithm. Its main goal is to help React better handle large applications, especially by improving application responsiveness through interruptible rendering.

Core Improvement: Before Fiber, React's rendering process couldn't be interrupted once started, potentially blocking the main thread and causing page lag. Fiber allows the rendering process to be interrupted to prioritize user interactions.

Key Features of Fiber Architecture

Interruptible and Resumable Work

Like writing a long report where you can pause to answer a phone call and then resume writing. React Fiber works similarly - when a user needs to click a button, it can pause the ongoing rendering work to prioritize responding to user interaction.

Priority Scheduling

Similar to hospital triage where critical patients are treated first. React prioritizes user interactions (like button click animations) over background data updates to ensure a good user experience.

Relationship Between Virtual DOM and React Fiber

Although Virtual DOM and React Fiber are different concepts, they work closely together in React:

AspectVirtual DOMReact Fiber
What is itJavaScript object representation of DOMReconciliation engine
PurposeDescribes what the UI should look likeDetermines how and when to update the UI
Update methodCompleted at onceSegmented, interruptible

Simple Understanding:

  • 1. Virtual DOM tells React 'what to do' (what the UI should look like)
  • 2. Fiber decides 'how to do it' (how to efficiently update the DOM)

Their combination allows React to provide both a good development experience (declarative programming) and excellent performance and responsiveness.

🔥 Common Interview Questions

(1) What is Virtual DOM and how does it improve React's performance?

Answer:

Virtual DOM is a JavaScript object representation of the real DOM. It's like a blueprint that describes the page structure but isn't the actual page.

Ways to improve performance:

  • 1. Batch updates: Calculate all changes in memory first, then update the real DOM at once
  • 2. Reduce operations: Only update parts that actually need to change, don't repaint the entire page
  • 3. Cross-platform: The same logic can render to different platforms like web pages and mobile apps

Simple example:

// Virtual DOM representation
const vdom = {
  type: 'div',
  props: { className: 'container' },
  children: [
    { type: 'h1', props: { children: 'Title' } },
    { type: 'p', props: { children: 'Content' } }
  ]
}

It's worth noting that Virtual DOM isn't always faster than direct DOM manipulation, but it allows developers to build complex UIs in a simpler way while maintaining reasonable performance.

(2) What is the purpose of React Fiber architecture? How did it improve React's rendering mechanism?

Answer:

The purpose of the Fiber architecture is to make React applications smoother, especially when handling large amounts of data and complex interfaces. It's like breaking a big job into small pieces that can be paused to handle more important things.

Main improvements:

  • 1. Interruptible rendering: Long tasks can be executed in segments without blocking the main thread
  • 2. Priority scheduling: User interactions can take priority over background updates
  • 3. Error handling: An error in one component won't crash the entire application

Old React

Complete all work at once\n↓\nMay cause page lag

Fiber Architecture

Break work into small pieces\n↓\nCan pause to handle important events\n↓\nPage remains responsive

Fiber divides rendering into two phases: the 'preparation phase' (interruptible) decides what changes to make, and the 'commit phase' (non-interruptible) applies changes to the DOM. This allows React to handle complex updates while keeping the page responsive.

(3) Explain the importance of the key prop in React and how to use it correctly?

Answer:

The key prop is like an 'ID card' for each item in a list, helping React identify which items have changed, been added, or deleted.

Why it's important:

  • 1. Helps React efficiently update lists without rebuilding all items
  • 2. Maintains component state, preventing loss during position changes
  • 3. Reduces unnecessary re-renders, improving performance

Correct usage:

// ❌ Bad: Using index as key
<ul>
  <li>Home</li>
  <li>About</li>
</ul>

// ✅ Good: Using unique ID
<ul>
  <li key="home">Home</li>
  <li key="about">About</li>
</ul>

Rules for using keys:

  • 1. Must be unique among siblings
  • 2. Should be stable, don't generate randomly
  • 3. Use data IDs when possible, avoid using indices

Using indices as keys can cause problems when item order changes, because the index changes but the content might not, leading React to misunderstand the situation. It's best to use stable IDs from the data as keys.

(4) Explain the Virtual DOM workflow, what happens in each phase?

Answer:

The Virtual DOM workflow can be divided into several key phases, each with specific tasks:

1. Create Virtual DOM Tree

React converts JSX into JavaScript objects, forming the virtual DOM tree.

// JSX
<div className="container">
  <h1>Title</h1>
</div>

// Converted to Virtual DOM object
{
  type: 'div',
  props: {
    className: 'container',
    children: [{
      type: 'h1',
      props: { children: 'Title' }
    }]
  }
}

2. Diffing Comparison Phase

When state updates, React creates a new virtual DOM tree and compares it with the old tree to find differences.

Old Tree

div (container)
  ├─ h1: "舊標題"
  └─ p: "舊內容"

New Tree

div (container)
  ├─ h1: "新標題"
  └─ p: "舊內容"

↓ Diff Result: Only need to update h1 text content

3. Reconciliation Phase

Based on the Diff results, React calculates the minimal changes needed for the DOM. This phase is interruptible, allowing the browser to handle higher priority tasks.

// Pseudocode: Work unit in reconciliation phase
{
  type: 'UPDATE',
  element: h1Element,
  newProps: { children: 'New Title' },
  priority: 'normal'
}

4. Commit Phase

Apply the calculated changes to the actual DOM. This phase is non-interruptible, once started it will complete all updates.

// Pseudocode: DOM update operation
h1Element.textContent = 'New Title';

5. Lifecycle and Hooks Execution

After DOM update:Execute useLayoutEffect

After browser paint:Execute useEffect

In simple terms, the whole process is like renovating a house:

  • 1. First draw the design on paper (Virtual DOM)
  • 2. Compare old and new designs, mark areas that need changes (Diffing)
  • 3. Plan construction sequence, can be done in phases (Reconciliation)
  • 4. Actually start renovating the house (Commit)
  • 5. Check construction results and make final adjustments (Lifecycle and Hooks)

This approach allows React to efficiently update the UI while maintaining a good user experience, especially in complex applications.