Integrating Rust WebAssembly into a React Application: A Step‑by‑Step Demo
This tutorial walks through building a simple React project, setting up Rust with Cargo and rustup, compiling Rust to WebAssembly using wasm‑bindgen and wasm‑pack, and finally importing the generated Wasm module into React components to demonstrate seamless Rust‑powered frontend functionality.
Introduction
Hello, I am ConardLi. After publishing a Wasm article about the Google I/O conference, I will now show how to integrate a Rust component into a React project with a small demo.
What is WebAssembly?
WebAssembly (Wasm) is a binary instruction format that runs on a stack‑based virtual machine. It serves as a portable compilation target for programming languages, enabling client‑side and server‑side applications to run on the web with near‑native performance.
Why Choose Rust?
Rust is a fast, memory‑safe language that has topped StackOverflow’s most‑loved list for years. Its advantages include memory safety, type safety, data‑race elimination, ahead‑of‑time compilation, minimal runtime, and suitability for low‑memory or bare‑metal environments. Rust also has strong WebAssembly support, making it easy to compile to Wasm.
Prerequisite Knowledge
Familiarity with React is assumed. You also need to understand a few Rust concepts:
cargo
cargois Rust’s package manager and build tool, analogous to npm for Node.js.
rustup
rustupmanages Rust toolchains and can install components such as rustc and cargo.
wasm‑bindgen
wasm‑bindgencreates a bridge between JavaScript and Rust types, allowing JS to call Rust APIs and vice‑versa.
wasm‑pack
wasm‑packis an active tool for packaging Rust‑generated WebAssembly for npm.
wasm32‑unknown‑unknown
This is the compilation target for producing generic WebAssembly binaries.
Step 1: Set Up a Simple React Project
Initialize a React project and install development dependencies:
$ npm init
$ npm i react react-dom
$ npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin
$ npm i -D babel-core babel-loader @babel/preset-env @babel/preset-reactCreate the folder structure src, page, public, build, and dist. Add page/index.jsx with a basic React render:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<h1>code秘密花园 Hello, world!</h1>, document.getElementById('root'));Configure Babel ( .babelrc) and Webpack ( webpack.config.js) as follows:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
} const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './page/index.jsx',
output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.[hash].js' },
devServer: { compress: true, port: 8080, hot: true, static: './dist', historyApiFallback: true, open: true },
module: { rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }] },
plugins: [new HtmlWebpackPlugin({ template: `${__dirname}/public/index.html`, filename: 'index.html' })],
mode: 'development',
devtool: 'inline-source-map'
};Add public/index.html with a root div and a matching package.json (see source for details).
Step 2: Prepare the Rust Project
Initialize a Rust library: cargo init --lib . Edit Cargo.toml to produce a cdylib and add wasm-bindgen:
[package]
name = "react-wasm"
version = "1.0.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"Write two simple exported functions in src/lib.rs:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" { fn alert(s: &str); }
#[wasm_bindgen]
pub fn big_computation() { alert("这个是一个超级耗时的复杂计算逻辑"); }
#[wasm_bindgen]
pub fn welcome(name: &str) { alert(&format!("Hi 我是 {},我在 code秘密花园!", name)); }Build the library for the Wasm target:
$ rustup target add wasm32-unknown-unknown
$ cargo build --target wasm32-unknown-unknownInstall the wasm-bindgen-cli tool and generate JS bindings:
$ cargo install -f wasm-bindgen-cli
$ wasm-bindgen target/wasm32-unknown-unknown/debug/react_wasm.wasm --out-dir buildStep 3: Connect Rust Wasm to React
Add npm scripts to package.json for building the Wasm module:
"build:wasm": "cargo build --target wasm32-unknown-unknown",
"build:bindgen": "wasm-bindgen target/wasm32-unknown-unknown/debug/react_wasm.wasm --out-dir build",
"build": "npm run build:wasm && npm run build:bindgen && npx webpack"Install the Webpack plugin for Wasm packaging and update webpack.config.js:
npm i -D @wasm-tool/wasm-pack-plugin
const WasmPackPlugin = require('@wasm-tool/wasm-pack-plugin');
// ... inside plugins array:
new WasmPackPlugin({ crateDirectory: path.resolve(__dirname, '.') }),
// enable async WebAssembly
experiments: { asyncWebAssembly: true }Finally, import the generated Wasm module in a React component and use the exported functions:
import React, { useState } from "react";
import ReactDOM from "react-dom";
const wasm = import("../build/react_wasm");
wasm.then(m => {
const App = () => {
const [name, setName] = useState("");
const handleChange = e => setName(e.target.value);
const handleClick = () => m.welcome(name);
return (
<>
<div>
<h1>Hi there</h1>
<button onClick={m.big_computation}>Run Computation</button>
</div>
<div>
<input type="text" onChange={handleChange} />
<button onClick={handleClick}>Say hello!</button>
</div>
</>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
});Run npm run build and start the development server. The React UI can now call Rust‑implemented WebAssembly functions, demonstrating a fast, memory‑safe integration.
References
https://www.rust-lang.org/learn
https://rustwasm.github.io/
https://www.joshfinnie.com/blog/using-webassembly-created-in-rust-for-fast-react-components/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
