So you want to use wasm_bindgen to add rust to you existing React app, or you're not quite ready for the rust web frameworks?
There are lots of examples out there demonstrating WASM for computationally intensive workloads, but how do you hook into React component rendering?
This crate wraps observable-rs, providing wasm_bindgen compatibility with React bindings
```javascript import React, { useMemo, useReducer } from "react"; import { useObserve } from "observable-rs";
function App({ wasm }: { wasm: any }) { let [listVisible, toggleShow] = useReducer((show: boolean) => { return !show }, true);
let [thing, thelist] = useMemo(() => { let thing = wasm.createrustthing(); setInterval(() => thing.dosomething(), 1000); return [thing, thing.getthelist()]; }, [wasm]);
return (
export default App;
function TheList({ thelist }: { thelist: any }) { // Bind this observable to the react component useObserve(the_list);
return (
First, follow the setup instructions here to create a react app with a bundled rust crate:
https://dev.to/lokesh007/webassembly-with-rust-and-react-using-create-react-app-67
NOTES:
* Suggest you use the typescript flag when creating your react app:
npx create-react-app your_react_app --template typescript
* Change .config-overrides.json extraArgs: "--no-typescript"
to extraArgs: ""
* your wasm build output dir (specified in config-overrides.json) must be inside or symlinked within your react app src directory in order to be bundled
Then:
```bash cd yourreactapp
npm i observable-rs
cd yourwasmcrate_dir
cargo add observable-react
cd yourreactapp npm serve ```
For a working example, see example react app
NOTE: Because wasm_bindgen is not currently able to bundle javascript helper functions, you must install the following npm package in your react app observable-rs