← blog

Boosting React Native Performance with Rust, JSI, and WASM

Recently, I’ve been deeply involved in integrating Rust, Java, and React Native, focusing on leveraging the new JavaScript Interface (JSI). This new architecture allows direct communication between JavaScript and native code, bypassing the traditional bridge and significantly reducing overhead.

The Challenge

In a recent project, I needed to integrate a Rust library with a React Native app. The conventional approach (Rust -> C (Shared Library) -> Java -> JS) was causing performance issues due to the heavy serialization/deserialization required for communication across these layers. This was particularly problematic on lower-end devices, where the lag was noticeable and led to a poor user experience. High-end devices like iPhones or the latest Samsung models handled the process better, but the discrepancy in performance across devices was significant.

The Solution

To address this, I explored WebAssembly (WASM) as an alternative. WASM allows Rust code to be compiled into a portable, binary format that JavaScript can execute directly, bypassing the need for C and Java layers. This approach streamlined the process and delivered a significant performance boost.

Pipeline for Direct Rust Integration via JSI

  1. Rust Code: Write core logic in Rust.
  2. Compile to Shared Library: Compile Rust to a C-compatible shared library (.so, .dll, .dylib).
  3. C Wrapper: Create a C wrapper that links to the Rust library.
  4. C++ JSI Binding: Implement a C++ layer to expose C functions to JSI.
  5. React Native Integration: Register C++ functions with JSI for direct JavaScript calls.
  6. JavaScript Usage: Call Rust functions directly from JavaScript.

JSI further enhanced this setup by eliminating the bridge overhead, allowing JavaScript to call native methods directly. This resulted in a smoother, more responsive experience, especially on lower-end devices.

Key Takeaways

This project highlighted the efficiency hierarchy of code from closest to furthest from machine code:

  1. C Code
  2. Rust Code
  3. WASM Code
  4. Java Code
  5. JavaScript Code

By leveraging JSI and WASM, we can achieve more consistent performance across devices, providing a better user experience regardless of hardware capabilities.

It’s been a fascinating journey diving into these technologies and seeing the tangible benefits they bring. I’m excited to continue exploring and pushing the boundaries of what’s possible!