/react-hooks-worker

React custom hooks for web workers

Primary LanguageJavaScriptMIT LicenseMIT

react-hooks-worker

Build Status npm version bundle size

React custom hooks for web workers.

Motivation

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.

Install

npm install react-hooks-worker

Usage

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>
);

Usage with Parcel

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);

Examples

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.

You can also try them in codesandbox.io: 01 02 03

Blogs