Use WebAssembly in React in a simple way with hooks and Typescript!
npm install use-wasm-ts
This package allows you to load and use your WebAssembly functions inside React easily.
import { FC } from 'react';
import { useWasm } from 'use-wasm-ts';
const MyComponent: FC = () => {
const {
isLoading,
fn: { compute },
} = useWasm<{ compute: (n: number) => number }>('compute.wasm');
return (
<>
<p>{isLoading ? "Loading..." : `Loaded with ${compute(10)}`}</p>
</>
);
};
export default MyComponent;
Show a live demo on CodeSandbox.
useWasm<T>(url: string, options?: useWasmOptions): {
isLoading: boolean;
fn: T;
module: WebAssembly.Module;
instance: WebAssembly.Instance;
memory: WebAssembly.Memory;
};
Type: string
The url of the WebAssembly file.
Type: useWasmOptions
The streaming option allows you to load the WebAssembly file in streaming mode. Before using it, make sure that your server serves the file with the correct MIME type.
The fetchOptions option allows you to pass options to the fetch function.
The memory option allows you to pass a custom memory to the WebAssembly file.
The env option allows you to pass a custom environment to the WebAssembly file. The function takes the default / custom memory as an optionnal parameter and must return an object.
MIT