@shopify/react-web-worker
TypeScript icon, indicating that this package has built-in type declarations

5.0.15 • Public • Published

@shopify/react-web-worker

Build Status Build Status License: MIT npm version npm bundle size (minified + gzip)

A hook for using web workers in React applications.

Installation

yarn add @shopify/react-web-worker

Usage

This package provides a useWorker hook to leverage web workers in React. For convenience, it also re-exports the entirety of @shopify/web-worker, so you only need to install this package to get access to those additional exports.

useWorker()

useWorker allows your React applications to take advantage of web workers provided by createWorkerFactory from @shopify/web-worker. This hook creates a web worker during render and terminates it when the component unmounts.

import React, {useEffect} from 'react';
import {Page} from '@shopify/polaris';
import {createWorkerFactory, useWorker} from '@shopify/react-web-worker';

// assume ./worker.ts contains
// export function hello(name) {
//  return `Hello, ${name}`;
// }

const createWorker = createWorkerFactory(() => import('./worker'));

function Home() {
  const worker = useWorker(createWorker);
  const [message, setMessage] = React.useState(null);

  useEffect(() => {
    (async () => {
      // Note: in your actual app code, make sure to check if Home
      // is still mounted before setting state asynchronously!
      const webWorkerMessage = await worker.hello('Tobi');
      setMessage(webWorkerMessage);
    })();
  }, [worker]);

  return <Page title="Home"> {message} </Page>;
}

You can optionally pass a second argument to useWorker, which will be used as the options to the worker creator function.

Dependencies (3)

Dev Dependencies (0)

    Package Sidebar

    Install

    npm i @shopify/react-web-worker

    Weekly Downloads

    32,903

    Version

    5.0.15

    License

    MIT

    Unpacked Size

    6.77 kB

    Total Files

    15

    Last publish

    Collaborators

    • jaimie.rockburn
    • blittle
    • shopify-admin
    • maryharte
    • crisfmb
    • pmoloney89
    • netlohan
    • st999999
    • justin-irl
    • megswim
    • wcandillon
    • nathanpjf
    • shopify-dep
    • goodforonefare
    • lemonmade
    • vsumner
    • wizardlyhel
    • antoine.grant
    • tsov
    • andyw8-shopify
    • henrytao
    • hannachen
    • vividviolet
    • bpscott