0Pricing
React Academy · Lesson

Rust to WASM with wasm-pack and React

Compile Rust code to WebAssembly with wasm-pack and consume the generated JS bindings in a React app.

Rust to WASM with wasm-pack and React is a free React Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Rust WASM Toolchain

The standard Rust-to-WASM workflow uses two tools: wasm-pack orchestrates the build (compiling Rust to WASM, running wasm-bindgen, generating the npm package), and wasm-bindgen generates JavaScript bindings that make Rust functions callable as regular JavaScript functions with proper type handling.

wasm-bindgen Attribute

The #[wasm_bindgen] attribute marks Rust functions, structs, and methods for export to JavaScript. Without it, the function is compiled to WASM but not accessible from JavaScript. When you annotate a function with #[wasm_bindgen], wasm-bindgen generates the JavaScript glue code that handles argument and return value conversion.

A Simple Rust Function

A minimal exported Rust function: use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a: u32, b: u32) -> u32 { a + b }. The function takes two unsigned 32-bit integers and returns one. wasm-bindgen generates JavaScript that calls this function with number arguments and returns a number result.

Building with wasm-pack

Run wasm-pack build --target web in the Rust crate directory. This compiles the Rust code to WASM, runs wasm-bindgen to generate JavaScript bindings, and outputs a pkg/ directory containing the .wasm binary, a JavaScript glue module, and TypeScript type definitions.

Importing in React

Import the generated module in your React component: import init, { add } from '../pkg/my_lib'. The init function loads and instantiates the WASM binary (call it once in a useEffect). After initialization, call the exported functions directly: const result = add(2, 3).

Passing Complex Data: js_sys and JsValue

For complex data beyond primitive numbers, wasm-bindgen provides js_sys::Array (JavaScript Array), js_sys::Object (JavaScript Object), and wasm_bindgen::JsValue (any JavaScript value). These types allow Rust functions to accept and return JavaScript arrays and objects, though with more serialization overhead than primitives.

Minimizing Marshalling Overhead

The key performance principle: keep data in WASM memory and do all computation there. Pass data in once, compute, and return only the final result. Avoid patterns that repeatedly transfer data across the WASM boundary for each step. The overhead per boundary crossing is small but accumulates in tight loops.

serde-wasm-bindgen for Structs

The serde-wasm-bindgen crate enables serializing Rust structs to and from JavaScript objects using Serde. Annotate the struct with #[derive(Serialize, Deserialize)] and use serde_wasm_bindgen::to_value() and from_value(). This is the standard approach for passing complex structured data.

Running WASM in a Web Worker

Long-running WASM computations block the thread they run on. Place WASM in a Web Worker to keep React's main thread free. Create a Worker file that initializes the WASM module and handles messages. Send data to the worker via postMessage, receive results via the message event, then update React state with the result.

TypeScript Types from wasm-pack

wasm-pack automatically generates TypeScript declaration files (.d.ts) for all exported functions and types. This gives your React TypeScript project full type safety when calling Rust functions. The generated types reflect the Rust function signatures — add(a: number, b: number): number — making IDE autocomplete work correctly.

Production Considerations

WASM binaries are typically 100kb-2MB after optimization. Enable wasm-opt in the wasm-pack build by setting opt-level = "z" in the Cargo.toml release profile for aggressive size optimization. Serve WASM files with Content-Type: application/wasm and enable HTTP/2 so the browser streams the binary efficiently.

wasm-bindgen Attribute

What is the purpose of the #[wasm_bindgen] attribute in Rust code?

Lesson Recap

wasm-pack build --target web compiles Rust to WASM and generates JavaScript bindings via wasm-bindgen. Annotate exported functions with #[wasm_bindgen]. Import init and the exported functions in React, call init() in a useEffect, then call functions as regular JavaScript. Use serde-wasm-bindgen for complex struct serialization. Run WASM in Web Workers for long computations to keep the React main thread free.

Frequently asked questions

Is the “Rust to WASM with wasm-pack and React” lesson free?

Yes — the full text of “Rust to WASM with wasm-pack and React” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Rust to WASM with wasm-pack and React”?

Compile Rust code to WebAssembly with wasm-pack and consume the generated JS bindings in a React app. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Rust to WASM with wasm-pack and React” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is WebAssembly and Where React Fits
  2. Loading WASM Modules in React
  3. Rust to WASM with wasm-pack and React
  4. WASM Use Cases: Image Processing and Computation
← Back to React Academy