InterviewHubPRO
Section Overview
Q306

Question 306 of 445

Part 9: React Hooks Deep Dive (262 - 316)

69%
React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

How does React Fiber works? Explain in detail.

React Fiber is the core engine that enables advanced features like concurrent rendering, prioritization, and interruptibility in React. Here's how it works:

1. Fiber Tree Structure

Each component in your app is represented by a Fiber node in a tree structure. A Fiber node contains:

  • Component type
  • Props & state
  • Pointers to parent, child, and sibling nodes
  • Effect tags to track changes (e.g., update, placement)
  • This forms the Fiber Tree, a data structure React uses instead of the traditional call stack.

2. Two Phases of Rendering

A. Render Phase (work-in-progress)

  • React builds a work-in-progress Fiber tree.
  • It walks through each component (begin phase), calculates what needs to change, and collects side effects (complete phase).
  • This phase is interruptible—React can pause it and resume later.

B. Commit Phase

  • React applies changes to the Real DOM.
  • Runs lifecycle methods (e.g., componentDidMount, useEffect).
  • This phase is non-interruptible but fast.

3. Work Units and Scheduling

  • React breaks rendering into units of work (small tasks).
  • These units are scheduled based on priority using the React Scheduler.
  • If time runs out (e.g., user starts typing), React can pause and yield control back to the browser.

4. Double Buffering with Two Trees

  • React maintains two trees:
  • Current Tree – what's visible on the screen.
  • Work-In-Progress Tree – the next version being built in memory.
  • Only after the new tree is fully ready, React commits it, making it the new current tree.

5. Concurrency and Prioritization

  • React can prepare multiple versions of UI at once (e.g., during slow data loading).
  • Updates can be assigned priorities, so urgent updates (like clicks) are handled faster than background work.

Practical Code Example

text
// React Fiber Architecture:
// 1. Reconciliation is split into Work Units
// 2. Render Phase: Asynchronous, interruptible, priority-based
// 3. Commit Phase: Synchronous, updates DOM in a single pass