Getting started with React + WebAssembly

Prerequisites

Let’s get a React app running

npx create-react-app wasm-react

Let’s write some C

#include <emscripten/emscripten.h>#include <stdlib.h>EMSCRIPTEN_KEEPALIVE int add(int a, int b){return a + b;}

Make a Makefile

src/add.mjs: src/add.cemcc --no-entry src/add.c -o src/add.mjs  \-s ENVIRONMENT='web'  \-s SINGLE_FILE=1  \-s EXPORT_NAME='createModule'  \-s USE_ES6_IMPORT_META=0  \-s EXPORTED_FUNCTIONS='["_add", "_malloc", "_free"]'  \-s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'  \-O3
emcc
source ./emsdk_env.sh
make

Bringing it all together

import React, { useState, useEffect } from "react";import createModule from "./add.mjs";function App() {  const [add, setAdd] = useState();
useEffect( () => { createModule().then((Module) => { setAdd(() => Module.cwrap("add", "number", ["number", "number"])); }); }, []); if (!add) { return "Loading webassembly..."; } return ( <div className="App"> <p>Let's do some basic addition:</p> <div>123 + 234 = {add(123, 234)}</div> </div> );}export default App;
return (  <div className="App">    <p>Let's do some basic addition:</p>    <div>123 + 234 = {add(123, 234)}</div>  </div>);
"ignorePatterns": [  "src/add.mjs"]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store