npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-worker-hooks

v0.5.1

Published

React hooks for running code inside web workers without needing to eject CRA apps.

Downloads

23

Readme

⚛️ web-worker-hooks

React hooks for running code inside web workers without needing to eject CRA apps.


Table of contents


Installation

npm install web-worker-hooks

Introduction

web-worker-hooks aims to provide simple but powerful easy-to-use hooks for running tasks in web workers without needing to eject apps bootstrapped with Create React App.

The library provides elegant drop-in replacements for setTimeout and setInterval. The useWorker hook gives you full control over Web Worker message passing. usePureWorker provides a clean way to run a compute intensive function in a worker thread, and unblock the UI.


Usage

This package provides a suite of hooks to perform background tasks in Web Workers.

Starting with the most general hook

  1. useWorker

function App() {
  const worker = useWorker((postMessage, setOnMessage) => {
    setOnMessage((msg) => {
      postMessage([msg.data, "Hello from worker."]);
    });
  });

  React.useEffect(() => {
    worker.onmessage = (msg) => {
      console.log(msg.data);
    };

    worker.postMessage("Hello from main.");
  }, []);

  ...
}

The function provided to the hook gets called immediately inside a web worker. It receives two arguments, postMessage which shadows the postMessage function available on the worker scope. And a setOnMessage function which can be used to set onmessage.

The hook returns a plain Worker object so all its methods are available for use.

  1. useWorkerTimeout

function App() {
  const [count, setCount] = React.useState(0);
  const clearTimeout = React.useRef(() => {});
  const workerSetTimeout = useWorkerTimeout();

  React.useEffect(() => {
    function startTimer() {
      clearTimeout.current = workerSetTimeout(startTimer, 1000);
      setCount((c) => c + 1);
    }
  }, []);

  return (
    <div>
      <div>{count}</div>
      <button onClick={() => clearTimeout.current()}>Stop Timer</button>
    </div>
  );
}

The hook takes no arguments and returns a near drop-in replacement for window.setTimeout. The main difference is that calling workerSetTimeout will return a function which can be called for clearing the timeout instead of needing to call window.clearTimeout.

  1. useWorkerInterval

Identical to useWorkerTimeout except that it calls setInterval.

  1. usePureWorker

function fib(n) {
  if (n < 2) {
    return n;
  }
  return fib(n - 1) + fib(n - 2);
}

function App() {
  const workerFib = usePureWorker(fib);

  React.useEffect(() => {
    workerFib(42).then((result) => console.log(result));
  }, []);

  ...
}

The usePureWorker hook can be used to easily create functions that can run a compute intensive pure-ish function when called and return a Promise which will resolve to the result of the computation from the worker.


Example

example gif


Limitations & Pitfalls

  1. The main limitation currently is that you cannot import external libraries into your workers. This can be a dealbreaker for your usecase so please consider it before installing. You may need to eject your CRA app if you must use a library inside your worker.
  2. There is an invisible barrier between the worlds of the function provided to useWorker or usePureWorker and the main thread. You cannot use any variables or functions defined outside, in the function you pass to run inside the web worker. The useWorkerTimeout and useWorkerInterval functions don't suffer from this shortcoming since they don't run the callback in a worker thread. Only the timer itself is run in the worker.

API Reference

useWorker

Import

import { useWorker } from "web-worker-hooks";

Parameters:

  1. workerFunction: (postMessage, setOnMessage) => void - workerFunction is a function that takes two arguments.
    • postMessage: (msg: any) => void - The function shadows the postMessage function on the worker scope.
    • setOnMessage: (messageHandler) => void - Pass it a handler to set onmessage on the worker.

Returns:

  1. Worker - The worker object. This is a standard web worker object that can be used from the main thread like you normally would.

useWorkerTimeout

Import

import { useWorkerTimeout } from "web-worker-hooks";

Returns:

  1. workerSetTimeout: (handler: Function, timeout: number) => cancelTimeout - A function that can be used much like window.setTimeout. It takes a handler and a timeout duration as arguments and returns a function that can be called to cancel the timer.

useWorkerInterval

Import

import { useWorkerInterval } from "web-worker-hooks";

Returns:

  1. workerSetInterval: (handler: Function, timeout: number) => cancelInterval - A function that can be used much like window.setInterval. It takes a handler and a timeout duration as arguments and returns a function that can be called to cancel the timer.

usePureWorker

Import

import { usePureWorker } from "web-worker-hooks";

Parameters:

  1. pureFunction: Function - A function that takes zero or more arguments and produces a result from them (without relying on external state).

Returns:

  1. workerPureFunction({ args, transfer = [] }) => Promise - An abstraction over running the supplied pure function in a web worker / background thread. The function takes a single object as argument with two properties:

    • args: any[] - A list of arguments that will be passed to the pure function call. NOTE: The pure function will not be passed the list itself, just the values as separate arguments.
    • transfer?: any[] - A list of Transferable values to transfer ownership. UNSTABLE: The API for this is still being worked out and will change.

    It returns a Promise that resolves to the result of the pure function.