Lesson 16-React Native Source Code Architecture

React Native Core Module Source Code

JavaScript and Native Bridging Mechanism (Bridge, TurboModules)

Bridge Communication Mechanism (Old Architecture)

// C++ Layer Bridge Core Implementation (Simplified)
class MessageQueueThread {
public:
  virtual void runOnQueue(std::function<void()>&& runnable) = 0;
};

class Bridge : public MessageQueueThread {
  // JS Calls Native Method
  void callNativeMethod(const std::string& moduleName, 
                       const std::string& methodName,
                       const folly::dynamic& params) {
    // 1. Convert JS Call to C++ Callable Task
    auto task = [=]() {
      // 2. Find Native Module
      auto module = getModule(moduleName);
      // 3. Invoke Native Method
      module->invoke(methodName, params);
    };
    
    // 4. Dispatch Task to Native Thread for Execution
    runOnQueue(std::move(task));
  }
};

TurboModules New Architecture

// TypeScript Type Definition (React Native 0.68+)
type ToastModuleSpec = {
  getName: () => string;
  show: (message: string, duration: number) => void;
};

// Auto-Generated C++ Header File (Simplified)
class JSIToastModule : public JSIHostObject {
public:
  void show(jsi::Runtime &rt, const jsi::String& message, double duration) {
    // Directly Call Native Method in JS Thread (No Bridge Required)
  }
};

Bridge Communication Process Comparison

FeatureBridge (Old)TurboModules (New)
Communication MethodAsynchronous Serialized Messages (JSON)Direct JSI Calls (Memory Sharing)
Thread ModelJS Thread → Native Thread (Serialization/Deserialization)JS Thread Directly Calls Native Method
Type SafetyRuntime Dynamic TypingCompile-Time Type Checking
PerformanceLower (Serialization Overhead)High (Zero-Copy)

Component Lifecycle Source Code Implementation

Component Mounting Process (ReactNativeFiber)

// C++ Layer Component Mounting Core Logic (Simplified)
void ComponentView::mountChildComponentView(
    const SharedComponentView& child,
    uint32_t index) {
  // 1. Create Native View
  auto nativeView = createNativeView();
  
  // 2. Apply View Properties
  applyProperties(nativeView, child->getProps());
  
  // 3. Add to View Hierarchy
  getParentView()->addSubview(nativeView, index);
}

// JavaScript Layer Lifecycle Mapping
class MyComponent extends React.Component {
  componentDidMount() { // Corresponds to C++ Layer Mount Operation
    console.log('Component Mounted');
  }
}

Lifecycle Method Call Chain

JavaScript Layer:
  constructor → static getDerivedStateFromProps → render → 
  componentDidMount (Mount Completed)

Native Layer Correspondence:
  createInstance → applyInitialProps → measure/layout → 
  mountComponentView → lifecycleEvent("componentDidMount")

Layout System Source Code Implementation (Flexbox)

Yoga Layout Engine Core Logic

// Yoga Node Layout Calculation (Simplified)
void YGNodeCalculateLayout(
    YGNodeRef node,
    float availableWidth,
    float availableHeight,
    YGDirection ownerDirection) {
  
  // 1. Calculate Own Dimensions
  if (node->getStyle().flexDirection == YGFlexDirectionRow) {
    node->setLayoutWidth(resolveWidth(node, availableWidth));
    node->setLayoutHeight(resolveHeight(node, availableHeight));
  }
  
  // 2. Recursively Calculate Child Nodes
  for (uint32_t i = 0; i < node->getChildrenCount(); i++) {
    YGNodeRef child = node->getChild(i);
    YGNodeCalculateLayout(
        child,
        node->getLayoutWidth(),
        node->getLayoutHeight(),
        node->getLayoutDirection());
  }
  
  // 3. Apply Flexbox Rules
  applyFlexDirection(node);
  applyJustifyContent(node);
  applyAlignItems(node);
}

Layout Property Mapping Table

React Native PropertyYoga PropertyCalculation Rule
flex: 1flexGrowDistribute Remaining Space Proportionally
alignItems: 'center'alignItemsCenter Children on Cross Axis
marginTop: 10margin[Top]Absolute Pixel Value

Event System Source Code Implementation

Touch Event Handling Process

// C++ Layer Touch Event Dispatch (Simplified)
void TouchEventHandler::dispatchTouchEvent(
    const TouchEvent& event) {
  
  // 1. Find Hit-Tested View
  auto targetView = hitTest(event.x, event.y);
  
  // 2. Build React Event Object
  jsi::Object reactEvent = createReactEvent(event);
  
  // 3. Call JavaScript Event Handler
  targetView->getEventEmitter()->dispatchEvent(
      "touchStart", 
      std::move(reactEvent));
}

// JavaScript Layer Event Handling
<View onTouchStart={(e) => console.log(e.nativeEvent)} />

Gesture Recognizer Architecture

GestureHandler System:
  - BaseGestureHandler (Base Class)
    ├── TapGestureHandler (Tap)
    ├── PanGestureHandler (Pan)
    ├── PinchGestureHandler (Pinch)
    └── RotationGestureHandler (Rotation)

React Navigation Core Architecture

Navigator Types:
  - StackNavigator (Stack Navigation)
  - TabNavigator (Tab Navigation)
  - DrawerNavigator (Drawer Navigation)

Core Components:
  - NavigationContainer (Navigation Root Container)
  - Navigator (Navigator Base Class)
  - Screen (Screen Component)

Route State Management

// Navigation State Tree Structure
{
  index: 0,          // Index of Currently Active Route
  routes: [          // Route Stack
    { key: 'Home', name: 'Home' },
    { key: 'Detail', name: 'Detail' }
  ]
}

Rendering and Performance Optimization Source Code

Virtual DOM and Diff Algorithm

Fiber Node Structure

struct FiberNode {
  FiberNode* parent;    // Parent Node
  FiberNode* child;     // First Child Node
  FiberNode* sibling;   // Sibling Node
  WorkTag tag;          // Component Type (FUNCTIONAL_COMPONENT, etc.)
  Props props;          // Component Properties
  State state;          // Component State
  Effect effectTag;     // Update Tag
};

Diff Algorithm Core Logic

// Simplified Fiber Reconciliation Process
void reconcileChildren(
    FiberNode* parent,
    Array<ReactElement> newChildren) {
  
  FiberNode* oldChild = parent->child;
  FiberNode* newChild = nullptr;
  
  while (oldChild || newChildIndex < newChildren.size()) {
    // 1. Key Matching Check
    if (oldChild && newChildren[newChildIndex].key == oldChild->key) {
      // Reuse Node (Update Props)
      updateFiber(oldChild, newChildren[newChildIndex]);
      oldChild = oldChild->sibling;
    } 
    // 2. Add New Node
    else if (newChildIndex < newChildren.size()) {
      newChild = createFiber(newChildren[newChildIndex]);
      appendChild(parent, newChild);
    }
    // 3. Delete Node
    else if (oldChild) {
      deleteFiber(oldChild);
      oldChild = oldChild->sibling;
    }
  }
}

List Rendering Optimization

FlatList Core Optimization Strategies

// Virtualized List Implementation Key Points:
1. Calculate Item Range for Visible Area (Viewport)
2. Render Only Visible Items (Recycle Invisible Item Views)
3. Dynamically Calculate Item Layout Positions (Avoid Global Measurement)
4. Batch Load Data (initialNumToRender)

// Memory Management:
- Use Recycler Component Pool to Reuse Item Views
- Dynamically Adjust windowSize (Rendering Window Size)

Animation Source Code Implementation

Animated Value Update Process

// JS → Native Animation Value Synchronization:
1. JavaScript Creates Animated.Value
2. Registers Animation Callback via Bridge/TurboModules
3. Native Animation Driver (AnimationDriver) Calculates Current Value
4. Notifies JavaScript to Update UI via Event System

// Performance Key Points:
- Uses Native Animation Thread (Avoids JS Thread Blocking)
- Value Interpolation Calculated on Native Side
- Supports Hardware Acceleration (e.g., transform Property)

Memory Management

Memory Leak Detection Mechanism

// Key Detection Points:
1. Check for Uncleaned Subscriptions During Component Unmount
2. Monitor Reference Counts for Native Modules
3. Detect Persistent References to JavaScript Objects

// Tool Implementation:
- Use Allocation Tracker to Track Memory Allocation
- Analyze via Heap Snapshot Comparison
- Integrate LeakCanary-Like Mechanism

Performance Monitoring

Performance Data Collection Points

// Key Metrics Collection:
1. JS Thread Frame Rate (FPS)
2. Native Module Call Duration
3. Layout Calculation Time
4. Memory Usage

// Data Reporting:
- Collect via Performance API
- Visualize with Flipper Plugins
- Integrate Sentry for Error Tracking
  1. New Architecture (Fabric & TurboModules):
    • Fabric: Enables Direct Communication Between JS and Native UI
    • TurboModules: Type-Safe Native Module Calls
    • CodeGen: Generates Type Definitions at Compile Time
  2. Rendering Optimization Directions:
    • Finer-Grained Component Updates
    • Enhanced List Virtualization
    • Animation Hardware Acceleration Optimization
  3. Toolchain Enhancements:
    • More Comprehensive Performance Analysis Tools
    • Automated Memory Leak Detection
    • Real-Time Performance Monitoring System

By deeply understanding the source code architecture, developers can:

  • Debug performance issues more efficiently
  • Design component structures rationally
  • Avoid common memory pitfalls
  • Fully leverage the advantages of the new architecture

Share your love