React custom hooks for web workers.
React Hooks API is promising. Web Workers API is promising.
This is an experimental library to provide an easy way to call web workers. It's more or less for fun, but feedbacks are welcome to make this for production.
npm install react-hooks-worker
import React from 'react';
import { useWorker } from 'react-hooks-worker';
const CalcFib = ({ count }) => {
const { result, error } = useWorker('./slow_fib.js', count);
if (error) return <div>Error:{error}</div>;
return <div>Result:{result}</div>;
};
const App = () => (
<div>
<CalcFib count={5} />
</div>
);
Parcel allow your Web Worker script to be automatically bundled. To do this, just pass an instance of the Web Worker instead of the url:
const myWorker = new Worker("./slow_fib.js")
const { result, error } = useWorker(myWorker, count);
The examples folder contains working examples. You can run one of them with
PORT=8080 npm run examples:minimal
and open http://localhost:8080 in your web browser.