react-native-specialist

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Native Specialist

React Native 专家

Purpose

用途

Provides React Native development expertise specializing in the "New Architecture" (Fabric/TurboModules), JSI, and Expo workflows. Builds high-performance cross-platform mobile applications with custom native modules and optimized JavaScript-to-native bridges.
提供专注于「新架构」(Fabric/TurboModules)、JSI和Expo工作流的React Native开发技术支持,可借助自定义原生模块与优化的JavaScript-原生桥接构建高性能跨平台移动应用。

When to Use

适用场景

  • Building high-performance React Native apps with the New Architecture
  • Writing custom Native Modules or View Managers (TurboModules/Fabric)
  • Configuring Expo pipelines (EAS Build, Updates, Config Plugins)
  • Debugging native crashes (Xcode/Android Studio) or bridge bottlenecks
  • Migrating from Old Architecture (Bridge) to New Architecture (JSI)
  • Integrating complex native SDKs (Maps, WebRTC, Bluetooth)
  • 基于新架构构建高性能React Native应用
  • 编写自定义原生模块或视图管理器(TurboModules/Fabric)
  • 配置Expo流水线(EAS Build、Updates、Config Plugins)
  • 调试原生崩溃(Xcode/Android Studio)或桥接瓶颈问题
  • 从旧架构(Bridge)迁移至新架构(JSI)
  • 集成复杂原生SDK(地图、WebRTC、蓝牙)

Examples

示例

Example 1: New Architecture Migration

示例1:新架构迁移

Scenario: Migrating a large production app from Bridge to Fabric/TurboModules.
Implementation:
  1. Enabled New Architecture flags progressively
  2. Converted Native Modules to TurboModules
  3. Implemented Fabric components for complex UIs
  4. Used Codegen to generate native bridge code
  5. Tested thoroughly with new architecture enabled
Results:
  • 40% faster UI rendering
  • 30% smaller bundle size
  • Improved type safety across native boundaries
  • Better crash reporting and debugging
场景: 将大型生产应用从Bridge架构迁移至Fabric/TurboModules架构。
实施步骤:
  1. 逐步启用新架构标识
  2. 将原生模块转换为TurboModules
  3. 为复杂UI实现Fabric组件
  4. 使用Codegen生成原生桥接代码
  5. 在启用新架构的环境下完成全面测试
结果:
  • UI渲染速度提升40%
  • 包体积减小30%
  • 跨原生边界的类型安全性提升
  • 崩溃报告与调试体验优化

Example 2: Custom Native Module

示例2:自定义原生模块

Scenario: Need to integrate Bluetooth Low Energy for a fitness app.
Implementation:
  1. Created TypeScript Native Module interface
  2. Implemented native code (Swift for iOS, Kotlin for Android)
  3. Exposed RNTurboModule for cross-platform access
  4. Added proper memory management and lifecycle handling
  5. Implemented comprehensive error handling
Results:
  • BLE operations working seamlessly on both platforms
  • Type-safe bridge prevents runtime errors
  • 50% less code than traditional native modules
  • Maintained through RN upgrades
场景: 为健身应用集成低功耗蓝牙(BLE)功能。
实施步骤:
  1. 创建TypeScript原生模块接口
  2. 实现原生代码(iOS用Swift,Android用Kotlin)
  3. 暴露RNTurboModule以支持跨平台访问
  4. 添加完善的内存管理与生命周期处理逻辑
  5. 实现全面的错误处理机制
结果:
  • BLE操作在双平台上无缝运行
  • 类型安全桥接避免运行时错误
  • 代码量比传统原生模块减少50%
  • 可兼容React Native版本升级

Example 3: Performance Optimization

示例3:性能优化

Scenario: App experiencing janky scrolling and memory issues.
Implementation:
  1. Enabled Hermes engine
  2. Replaced FlatList with FlashList
  3. Implemented memoization (useMemo, useCallback)
  4. Added lazy loading for images and heavy components
  5. Optimized native bridge communication
Results:
  • Scrolling now consistently 60fps
  • Memory usage reduced by 40%
  • App launch time reduced by 35%
  • Crash rate reduced by 60%
场景: 应用出现滚动卡顿与内存问题。
实施步骤:
  1. 启用Hermes引擎
  2. 用FlashList替代FlatList
  3. 实现记忆化优化(useMemo、useCallback)
  4. 为图片与重型组件添加懒加载
  5. 优化原生桥接通信
结果:
  • 滚动帧率稳定保持60fps
  • 内存占用降低40%
  • 应用启动时间缩短35%
  • 崩溃率降低60%

Best Practices

最佳实践

Architecture

架构

  • New Architecture: Enable and use Fabric/TurboModules
  • Native Modules: Use Codegen for type safety
  • Navigation: Use React Navigation or Expo Router
  • State Management: Choose appropriate solution (Zustand, Redux)
  • 新架构:启用并使用Fabric/TurboModules
  • 原生模块:使用Codegen保障类型安全
  • 导航:使用React Navigation或Expo Router
  • 状态管理:选择合适的解决方案(Zustand、Redux)

Performance

性能

  • Hermes: Enable for better startup and runtime
  • Memoization: Use useMemo, useCallback, React.memo
  • Lists: Use FlashList for large lists
  • Images: Lazy load and cache appropriately
  • Hermes:启用以提升启动速度与运行性能
  • 记忆化:使用useMemo、useCallback、React.memo
  • 列表:大型列表使用FlashList
  • 图片:合理实现懒加载与缓存

Native Integration

原生集成

  • Lifecycle Management: Handle app state changes
  • Error Boundaries: Catch native errors gracefully
  • Permissions: Request and handle gracefully
  • Testing: Test on both platforms regularly
  • 生命周期管理:处理应用状态变化
  • 错误边界:优雅捕获原生错误
  • 权限处理:合理申请与处理权限
  • 测试:定期在双平台进行测试

Development

开发流程

  • Expo Workflow: Use Expo for faster development
  • EAS Build: Use for CI/CD builds
  • Updates: Use EAS Update for over-the-air updates
  • TypeScript: Use for all code


  • Expo工作流:使用Expo加速开发
  • EAS Build:用于CI/CD构建
  • 更新机制:使用EAS Update实现空中更新
  • TypeScript:所有代码均使用TypeScript编写


2. Decision Framework

2. 决策框架

Architecture Selection

架构选择

Which architecture to use?
├─ **New Architecture (Default for 0.76+)**
│  ├─ **TurboModules:** Lazy-loaded native modules (Sync/Async).
│  ├─ **Fabric:** C++ Shadow Tree for UI (No bridge serialization).
│  ├─ **Codegen:** Type-safe spec for Native <-> JS communication.
│  └─ **Bridgeless Mode:** Removes the legacy bridge entirely.
└─ **Old Architecture (Legacy)**
   ├─ **Bridge:** Async JSON serialization (Slow for large data).
   └─ **Maintenance:** Only for unmigrated legacy libraries.
Which architecture to use?
├─ **New Architecture (Default for 0.76+)**
│  ├─ **TurboModules:** Lazy-loaded native modules (Sync/Async).
│  ├─ **Fabric:** C++ Shadow Tree for UI (No bridge serialization).
│  ├─ **Codegen:** Type-safe spec for Native <-> JS communication.
│  └─ **Bridgeless Mode:** Removes the legacy bridge entirely.
└─ **Old Architecture (Legacy)**
   ├─ **Bridge:** Async JSON serialization (Slow for large data).
   └─ **Maintenance:** Only for unmigrated legacy libraries.

Expo vs CLI

Expo vs CLI

FeatureExpo (Managed)React Native CLI (Bare)
SetupInstant (
create-expo-app
)
Complex (JDK, Xcode, Pods)
Native CodeConfig Plugins (Auto-modifies native files)Direct file editing (
AppDelegate.m
)
Upgrades
npx expo install --fix
(Stable sets)
Manual diffing (Upgrade Helper)
BuildsEAS Build (Cloud)Local or CI (Fastlane)
UpdatesEAS Update (OTA)CodePush (Microsoft)
特性Expo(托管式)React Native CLI(裸工程)
初始化快速完成(
create-expo-app
配置复杂(需JDK、Xcode、Pods)
原生代码配置插件(自动修改原生文件)直接编辑文件(如
AppDelegate.m
版本升级
npx expo install --fix
(稳定版本集)
手动对比代码(使用Upgrade Helper)
构建方式EAS Build(云端构建)本地或CI构建(如Fastlane)
更新机制EAS Update(空中更新)CodePush(微软提供)

Performance Strategy

性能优化策略

  1. JSI: Direct C++ calls. No JSON serialization.
  2. Reanimated: UI thread animations (Worklets).
  3. FlashList: Recycling views (replaces FlatList).
  4. Hermes: Bytecode precompilation (Instant startup).
Red Flags → Escalate to
mobile-developer
(Native):
  • Modifying the React Native engine core (C++)
  • Debugging obscure ProGuard/R8 crashes
  • Writing low-level Metal/OpenGL renderers from scratch


  1. JSI: 直接C++调用,无需JSON序列化。
  2. Reanimated: UI线程动画(Worklets)。
  3. FlashList: 视图复用(替代FlatList)。
  4. Hermes: 字节码预编译(启动速度更快)。
红色预警 → 升级至「mobile-developer(原生开发)」:
  • 修改React Native引擎核心(C++层)
  • 调试复杂的ProGuard/R8崩溃问题
  • 从零编写底层Metal/OpenGL渲染器


3. Core Workflows

3. 核心工作流

Workflow 1: Creating a TurboModule (New Arch)

工作流1:创建TurboModule(新架构)

Goal: Access native battery level synchronously via JSI.
Steps:
  1. Define Spec (
    NativeBattery.ts
    )
    typescript
    import type { TurboModule } from 'react-native';
    import { TurboModuleRegistry } from 'react-native';
    
    export interface Spec extends TurboModule {
      getBatteryLevel(): number;
    }
    
    export default TurboModuleRegistry.getEnforcing<Spec>('RTNBattery');
  2. Generate Code
    • Run
      yarn codegen
      . Generates C++ interfaces.
  3. Implement iOS (
    RTNBattery.mm
    )
    objectivec
    - (NSNumber *)getBatteryLevel {
      [UIDevice currentDevice].batteryMonitoringEnabled = YES;
      return @([UIDevice currentDevice].batteryLevel);
    }
    
    - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
        (const facebook::react::ObjCTurboModule::InitParams &)params {
      return std::make_shared<facebook::react::NativeBatterySpecJSI>(params);
    }
  4. Implement Android (
    BatteryModule.kt
    )
    kotlin
    class BatteryModule(context: ReactApplicationContext) : NativeBatterySpec(context) {
      override fun getName() = "RTNBattery"
      
      override fun getBatteryLevel(): Double {
        val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        return manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toDouble()
      }
    }


目标: 通过JSI同步获取原生设备电池电量。
步骤:
  1. 定义规范(
    NativeBattery.ts
    typescript
    import type { TurboModule } from 'react-native';
    import { TurboModuleRegistry } from 'react-native';
    
    export interface Spec extends TurboModule {
      getBatteryLevel(): number;
    }
    
    export default TurboModuleRegistry.getEnforcing<Spec>('RTNBattery');
  2. 生成代码
    • 运行
      yarn codegen
      ,生成C++接口。
  3. iOS端实现(
    RTNBattery.mm
    objectivec
    - (NSNumber *)getBatteryLevel {
      [UIDevice currentDevice].batteryMonitoringEnabled = YES;
      return @([UIDevice currentDevice].batteryLevel);
    }
    
    - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
        (const facebook::react::ObjCTurboModule::InitParams &)params {
      return std::make_shared<facebook::react::NativeBatterySpecJSI>(params);
    }
  4. Android端实现(
    BatteryModule.kt
    kotlin
    class BatteryModule(context: ReactApplicationContext) : NativeBatterySpec(context) {
      override fun getName() = "RTNBattery"
      
      override fun getBatteryLevel(): Double {
        val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        return manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toDouble()
      }
    }


Workflow 3: Reanimated Worklets

工作流3:Reanimated Worklets

Goal: 60fps drag gesture on the UI thread.
Steps:
  1. Setup
    tsx
    import { useSharedValue, useAnimatedStyle, withSpring } from 'react-native-reanimated';
    import { GestureDetector, Gesture } from 'react-native-gesture-handler';
  2. Implementation
    tsx
    function Ball() {
      const offset = useSharedValue({ x: 0, y: 0 });
    
      const gesture = Gesture.Pan()
        .onUpdate((e) => {
          // Runs on UI thread
          offset.value = { x: e.translationX, y: e.translationY };
        })
        .onEnd(() => {
          offset.value = withSpring({ x: 0, y: 0 }); // Snap back
        });
    
      const style = useAnimatedStyle(() => ({
        transform: [{ translateX: offset.value.x }, { translateY: offset.value.y }]
      }));
    
      return (
        <GestureDetector gesture={gesture}>
          <Animated.View style={[styles.ball, style]} />
        </GestureDetector>
      );
    }


目标: 在UI线程实现60fps的拖拽手势动画。
步骤:
  1. 初始化
    tsx
    import { useSharedValue, useAnimatedStyle, withSpring } from 'react-native-reanimated';
    import { GestureDetector, Gesture } from 'react-native-gesture-handler';
  2. 实现代码
    tsx
    function Ball() {
      const offset = useSharedValue({ x: 0, y: 0 });
    
      const gesture = Gesture.Pan()
        .onUpdate((e) => {
          // Runs on UI thread
          offset.value = { x: e.translationX, y: e.translationY };
        })
        .onEnd(() => {
          offset.value = withSpring({ x: 0, y: 0 }); // Snap back
        });
    
      const style = useAnimatedStyle(() => ({
        transform: [{ translateX: offset.value.x }, { translateY: offset.value.y }]
      }));
    
      return (
        <GestureDetector gesture={gesture}>
          <Animated.View style={[styles.ball, style]} />
        </GestureDetector>
      );
    }


5. Anti-Patterns & Gotchas

5. 反模式与注意事项

❌ Anti-Pattern 1: "Bridge Crossing" Animations

❌ 反模式1:「跨桥接」动画

What it looks like:
  • Using
    Animated.timing
    with
    useNativeDriver: false
    .
  • Calculating layout in
    useEffect
    and
    setState
    .
Why it fails:
  • Runs on JS thread. Drops frames if JS is busy (fetching data).
Correct approach:
  • Use Reanimated or
    useNativeDriver: true
    .
表现:
  • 使用
    Animated.timing
    且设置
    useNativeDriver: false
  • useEffect
    setState
    中计算布局
问题:
  • 运行在JS线程,若JS线程繁忙(如数据请求)会丢帧
正确方案:
  • 使用Reanimated或设置
    useNativeDriver: true

❌ Anti-Pattern 2: Large Bundles without Hermes

❌ 反模式2:未启用Hermes的大包体积

What it looks like:
  • JSC (JavaScriptCore) used on Android.
  • Startup takes 5 seconds.
Why it fails:
  • JSC parses JS at runtime. Hermes runs precompiled bytecode.
Correct approach:
  • Enable Hermes in
    podfile
    /
    build.gradle
    (Default in new Expo).
表现:
  • Android端使用JSC(JavaScriptCore)
  • 应用启动耗时5秒以上
问题:
  • JSC在运行时解析JS,Hermes运行预编译字节码
正确方案:
  • podfile
    /
    build.gradle
    中启用Hermes(新版Expo默认启用)

❌ Anti-Pattern 3: Styles in Render

❌ 反模式3:在渲染函数中定义样式

What it looks like:
  • style={{ width: 100, height: 100 }}
Why it fails:
  • Creates new object every render. Forces diffing.
Correct approach:
  • StyleSheet.create
    or
    const style = { ... }
    outside component.


表现:
  • 直接写
    style={{ width: 100, height: 100 }}
问题:
  • 每次渲染都会创建新对象,强制触发差异对比
正确方案:
  • 使用
    StyleSheet.create
    或在组件外部定义
    const style = { ... }


7. Quality Checklist

7. 质量检查清单

Performance:
  • Hermes: Enabled.
  • Memoization:
    useMemo
    /
    useCallback
    used for expensive props.
  • Lists:
    FlashList
    used instead of
    FlatList
    .
Architecture:
  • New Arch: Fabric/TurboModules enabled (if libraries support).
  • Navigation: Native screens used (React Navigation / Expo Router).
Native:
  • Permissions: Handled gracefully (not crashing if denied).
  • Upgrades: React Native version is recent (within 2 minor versions).
性能:
  • Hermes: 已启用
  • 记忆化: 对开销大的属性使用
    useMemo
    /
    useCallback
  • 列表: 使用
    FlashList
    替代
    FlatList
架构:
  • 新架构: 已启用Fabric/TurboModules(若依赖库支持)
  • 导航: 使用原生屏幕导航(React Navigation / Expo Router)
原生集成:
  • 权限处理: 优雅处理权限(被拒绝时不崩溃)
  • 版本更新: React Native版本较新(不超过2个小版本)

Anti-Patterns

反模式汇总

Architecture Anti-Patterns

架构反模式

  • Bridge Overuse: Heavy use of Old Architecture bridge - migrate to New Architecture
  • Unnecessary Native: Pure JS logic wrapped in native - keep it simple
  • State Management Sprawl: Multiple conflicting state solutions - standardize on one
  • Navigation Nesting: Deeply nested navigators - keep navigation shallow
  • 过度使用桥接: 大量依赖旧架构桥接 - 迁移至新架构
  • 不必要的原生封装: 纯JS逻辑被封装为原生模块 - 保持实现简洁
  • 状态管理混乱: 同时使用多种冲突的状态方案 - 统一为一种方案
  • 导航嵌套过深: 导航器层级过深 - 简化导航结构

Performance Anti-Patterns

性能反模式

  • Re-render Everything: No React.memo or optimization - optimize component re-renders
  • FlatList Abuse: Using FlatList for all lists - use appropriate list components
  • Memory Leaks: Not cleaning up subscriptions - use cleanup in useEffect
  • Bridge Bottleneck: Heavy bridge communication - minimize cross-bridge calls
  • 全局重渲染: 未使用React.memo或其他优化 - 优化组件重渲染逻辑
  • FlatList滥用: 所有列表都使用FlatList - 选择合适的列表组件
  • 内存泄漏: 未清理订阅 - 在useEffect中添加清理逻辑
  • 桥接瓶颈: 频繁跨桥接通信 - 减少跨桥接调用

Development Anti-Patterns

开发反模式

  • Debug Mode in Production: Not building for production - always test production builds
  • No Hermes: Not using Hermes engine - enable for better performance
  • Large Bundles: No bundle optimization - use RAM bundles and compression
  • Manual Linking: Manual native linking when not needed - use autolinking
  • 生产环境使用调试模式: 未构建生产包 - 始终测试生产构建
  • 未启用Hermes: 未使用Hermes引擎 - 启用以提升性能
  • 大包体积未优化: 未对包体积进行优化 - 使用RAM包与压缩
  • 手动链接原生库: 不必要的手动原生链接 - 使用自动链接

Testing Anti-Patterns

测试反模式

  • No E2E Testing: Only unit tests - add Maestro or Detox tests
  • Platform Conditionals: Too many platform checks - abstract platform differences
  • Hardcoded Dimensions: Fixed pixel values - use relative sizing
  • Missing testID: No accessibility identifiers - add testID for testing
  • 无E2E测试: 仅做单元测试 - 添加Maestro或Detox测试
  • 过多平台判断: 大量平台条件分支 - 抽象平台差异
  • 硬编码尺寸: 使用固定像素值 - 使用相对尺寸
  • 缺少testID: 无可访问性标识 - 添加testID用于测试