Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Understanding the Internal Structure of React ...

Avatar for calloc134 calloc134
June 22, 2025
17

Understanding the Internal Structure of React (React Tokyo #6 - @calloc134)

Avatar for calloc134

calloc134

June 22, 2025
Tweet

More Decks by calloc134

Transcript

  1. calloc134 @calloc134  Twitter: @calloc134  GitHub: @calloc134  Zenn:

    @calloc134 Profile U Interested in everything from front-end to infrastructure. x A note: As a student, I want to make the most of my time this year to do things I can only do now.
  2. Table of Contents Introduction What is Declarative UI? Implementing Declarative

    UI in React React’s Rendering Flow The True Nature of the Virtual DOM: Fiber Node Structure of Fiber Node Role of FiberRootNode Priority: Lane Rendering Phases (Trigger/Scheduler/Render/Commit) Summary
  3. Introduction What React Achieves A library for describing declarative UIs.

    React is the de facto standard UI library. However, many users don’t realize how React actually works under the hood. In this session, I’ll explain its mechanisms by walking through the source code.  Declaration in Code   React Internal Processing   UI Generation
  4. What is Declarative UI? What is declarative? Focus on WHAT

    to achieve, not HOW to do it. Example: Comparing tasks of drawing a rectangle on a canvas Imperative Approach Put down the pen. Draw a line to the right. Underline Draw a line to the left. Draw a line above. Describe each step of the operation in detail. Declarative approach Declare "Draw a rectangle on the canvas" Declare only what you aim to achieve.  Imperative UI  Declarative UI (React)
  5. Implementing Declarative UI in React (1) React achieves efficient rendering

    with a virtual DOM and change detection. Virtual DOM → Lightweight sketch paper Actual DOM → Final canvas Example: There is already an illustration of an octopus on the canvas, and I want to make it so that only the last leg is raised. 1 1 Clear all canvases and redraw.  Inefficient Redraw the entire thing, including the parts that have not changed. 2 Manually update only the changed parts. 2 Manually update only the changed parts.  Efficient but labor-intensive It is necessary to identify and update the modified parts. 3 React method 3 Detect and update differences in the draft Draft 1 Draft 2  Difference detection  Efficient and requires little effort Automatically detect and update only the difference s → React method React method
  6. Implementing Declarative UI in React (2) React's Approach Using the

    draft, everything is redrawn, but only the differences are applied to the actual canvas. * This part is handled by React. There is already an illustration of an octopus in the draft. 1 Sketch a new octopus that has only raised its last leg. 2 Compare Two Drafts and Find the Differences* 3 Apply only differences to actual canvas* 4 Simple summary In this way, developers can declaratively describe "what to achieve" without being conscious of the detailed procedures. → Significant improvement in developer experience Draft 1 (Current State) Draft 2 (Updated Version)  D ifference detection Actual canvas ( only differences applied)
  7. React’s Rendering Flow Consists of four phases to achieve efficient

    UI updates.  Trigger Phase Event Trigger  Trigger Phase Trigger the start of rendering Event Trigger  Schedule Phase Manages task prioritization and Execute Priority Assessment  Schedule Phase Manages task prioritization and Execute Priority Assessment  Render Phase Fiber Update Interruptible  Render Phase Builds virtual DOM and diffs Fiber Update Interruptible  Commit Phase DOM Update Cannot be interrupted  Commit Phase Applies changes to the real DOM DOM Update Cannot be interrupted
  8. Fiber Nodes: The Real Virtual DOM (1) What is managed

    internally by React is not the virtual DOM, but a tree of objects called "Fiber nodes" (Fiber tree). ※ The term "virtual DOM" is technically inaccurate.  Fiber nodes are the basic elements that make up the component tree. Main Properties of Fiber Node Property Name Explanation key Unique identifier of the component Used for element matching during re-rendering tag Component Type Function components, class components, DOM elements, etc. stateNode Instance of a component Actual corresponding DOM nodes or class instances, etc.
  9. Structure of Fiber Node (2) Reference relationships between fiber nodes

     child Reference to the Fiber node corresponding to the first child  sibling Reference to the next sibling Fiber node with the same parent  return Reference to the parent Fiber node  sibling A key point is that you can traverse sibling nodes like a linked list. A B1 B2 C child sibling child return return return
  10. Structure of Fiber Node (3) alternate: Reference to the corresponding

    other node of the two Fiber nodes (null if it doesn't exist) 1 React's rendering takes shape while maintaining two Fiber trees. 2 A node in the other tree that corresponds to the same entity as itself. 3 Something like a pointer for connecting with one's parallel world self 4 During the initial rendering, there is no node corresponding to current, so the alternate is null. Header (current) Nav (current) Main (current) Header (WIP) Nav (WIP) Main (WIP) alternate current Tree workInProgress Tree Two trees like parallel worlds, and the alternate reference that connects corresponding nodes. Two trees like parallel worlds, and the alternate reference that connects corresponding nodes.
  11. Role of FiberRootNode FiberRootNode is created during the initial render

    Two trees related to rendering: current and workInProgress current → Tree representing the UI on screen workInProgress → Tree being built for the next rendering FiberRootNode.current always points to the tree current A node that exists on top of the Fiber tree and manages the Fiber tree. There is always only one FiberRootNode Root FiberRootNode current tree Tree workInProgress current property
  12. Priority: Lane Represent priority internally as a 32-bit bitmask. Implement

    processing according to priority, as if tasks are like cars running in separate "lanes."  Update User Input → High Priority  Animation → Medium Priority  Background Update → Low Priority Priority expressed as "lane" Lane High Priority    Medium priority   Low priority        The advantage of expressing in binary → Priority can be combined using OR operations. Input processing: 0 0 1 0 0 ... Animation: 0 1 0 0 0 ... OR operation: 0 1 1 0 0 ...  It is possib le to represent tasks with multiple priorities using OR operations, allowing for efficient priority merging. 0 0 1 0 0 ... 0 1 0 0 0 ... OR operation: 0 1 1 0 0 ...
  13. Trigger Phase (1) Decide to start rendering and register it

    as a task Queue for managing tasks → Use a priority queue Structure of a Priority Queue It is possible to add a new element at the end. Items with higher priority are retrieved preferentially. There are two types of queues depending on the task taskQueue: A queue that manages tasks to be executed immediately timerQueue: A queue that manages tasks scheduled for future execution Diagram of a Priority Queue 1 2 3 7 A structure that is automatically sorted based on priority Types of Task Queues taskQueue Priority Tall  Deadline Recent Tasks that need immediate execution timerQueue Start time Future  Scheduled Standby Scheduled Tasks Scheduled for the Future
  14. Trigger Phase (2) Create Task Object Scheduled Task Start Time

    Scheduled Start Time of Task Timeout value (Maximum delay time) A value indicating how long a task can be postponed Expiration Time task start time + Timeout value Other Information: Task ID, execution function, etc.  Creation of Task Object Registration to the Queue 1 2 3 timerQueue Task B Task D ... Future tasks to be executed taskQueue Task A Task C ... Immediate execution task Task Object Scheduled start time, timeout value, expiration time, etc. 1 Confirmation of Start Time Is the task start time in the future or the past compared to the current time? 2 In the case of the future Register in timerQueue Key: Start Time In the case of the past Register in taskQueue Key: Expiration Time 3
  15. Schedule Phase Determine execution by retrieving tasks from the queue.

    A system for efficient task processing according to priority Flow of Task Acquisition and Execution peek Retrieve the top task (without removing it) Suspend if there is leeway & processing should be returned to the host environment. If not → Execute task When the task is completed pop Remove from queue If it is not completed, replace the function and it will remain in the queue.  Why is scheduling necessary? To prevent UI updates from being blocked by long-running tasks, break down processing into smaller chunks and create opportunities to return control to the browser. Task Queue Operations Task Execution Flow 1 peek() - Task Reference  2 Decision - Execute or Abort  Interruption  Execute  pop() Only upon completion Task A Priority: High peek → Task B Priority: Medium Task C Priority: Low taskQueue
  16. Render Phase (1) Updating the virtual DOM & detecting differences

    (reconciliation) beginWork: Function component execution, difference detection completeWork: Flag registration and DOM generation  Note: The explanation has been significantly simplified due to the extensive content. The initial rendering is uninterrupted. Interrupt as needed from the second time onward. Node traversal using Depth-First Search. Due to lack of time, this will be omitted this time... beginWork and completeWork are executed only once at each node.
  17. Render Phase (2) beginWork Edition beginWork: Main Role Responsible for

    executing function components and detecting differences. In the case of function components In the case of DOM elements Due to the simplicity of the process, detailed explanations are omitted in this document.  Details such as optimization processing (bailout) for efficiency are omitted. Run the component to obtain the element. Merge child element flags Reconciliation (Difference Detection Process) Function Component Execution Flow  Function Component Execution  Return element return <div> </div> ... ;    Reconciliation Detection of Differences Between Fiber Nodes and Result Elements
  18. Render Phase (3) Reconciliation Part (1) Reconciliation is essential for

    detecting differences. Compare the current Fiber node and the rendering result element For array elements: First, match based on position. All keys and types match → Matching successful If the matching fails: Fiber nodes become surplus → → Assigning a flag to delete surplus Fiber nodes Deletion of elements Excess elements → → Create a new Fiber node and assign a flag Add new elements Both are surplus → Matching → Proceed to the second stage failure Example of Location-Based Matching Matching successful Current Fiber Node A B C New element A B C ✓ ✓ ✓ Examples of Matching Failures Element Deletion A A B B C None Delete surplus fiber node Add element A A B B None C Create New Fiber Node Mismatch A A B D C C Transition to the second stage
  19. Render Phase (4) Reconciliation Part (2) Matching using keys Second-stage

    processing when location-based matching fails U Create an associative array: with keys → key Use, none → index Use U When a match is successful alternate Reuse existing nodes using properties U Achieve efficient differential detection through two-stage matching. 1. Location-based matching oldFiber[0] A ≠ newChild[0] D  Failed to compare in index 2. Key-based Matching Second Stage key: "b" D Search by key  "b" → B oldFiber B  newFiber D  Elements that successfully matched with the key are alternate Reuse using
  20. Render Phase (5) completeWork Edition completeWork: Flag registration and DOM

    generation Processing for DOM elements: In the case of function components, do nothing in particular. Finally, as a common process, merge the flags for the parent node. Efficient updates are achieved by propagating the flag information of child nodes to the parent. stateNode Register DOM node to property Register related flag 1. Register the DOM node in stateNode Fiber Node type: 'div' stateNode DOM Node <div id="root"> Fiber Node type: 'div' stateNode DOM Node <div id="root"> 2. Register the flag in flags. flags: 0 flags: 4 flags: 0  flags: 4 3. Merge the flag into the parent node. Parent Node 0 Child A 4 Child B 8 12 After flag merge Parent Node 0 Child A 4 Child B 8 12 After flag merge
  21. Commit Phase Reflect the differences in the actual DOM. The

    commit phase is the stage where the render results are applied to the actual UI. Check and reflect the flags set on the Fiber node This phase is Cannot be interrupted (Once it starts, it continues until completion) DOM manipulation, reference updates, lifecycle method calls, etc. Important Processing at the Time of Commit Completion After all the reflections are completed, FiberRootNode.current to workInProgress Updated → As a result, in the next rendering, the currently displayed state will be treated as the "current state." Before committing The current of FiberRootNode points to the old tree. FiberRootNode current current tree workInProgress Tree  After committing FiberRootNode.current = workInProgress; FiberRootNode current New current tree
  22. Summary  Declarative UI Focus on "what to achieve" 

    Fiber Tree Comparison Detect and update the differences between the two drafts.  Four Phases Trigger, Schedule, Render, Commit  DFS Search Utilizing efficient algorithms for DOM generation and difference detection  Reflect only the differences. Reflect only the differences in the actual DOM during the commit phase.
  23. Conclusion and References The source code of React is vast,

    and it is naturally possible to implement applications without reading it. However, there is no doubt that you can understand React's behavior more deeply by reading the source code. If you would like to know more details about this topic, please be sure to check out the blog article. Lastly, to the Meta React development team. Please feel free to point out if my interpretation of the source code is incorrect. That is extremely helpful. And thank you very much for providing the wonderful library. Looking forward to the future development of React! Reference Material  https://deepwiki.com/facebook/react  https://zenn.dev/ktmouk/articles/68fefedb5fcbdc  https://jser.dev/series/react-source-code-walkthrough  https://incepter.github.io/how-react-works/