### Install dependencies Source: https://github.com/alewin/useworker/blob/master/docs/CONTRIBUTE.md Install project dependencies for the first time. ```bash pnpm install ``` -------------------------------- ### Options example with timeout and remoteDependencies Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/useworker.md Example showing how to configure the worker with a timeout and remote dependencies. Note: the code has a missing comma after the timeout property. ```javascript import { useWorker } from "@koale/useworker"; const fn = dates => dates.sort(dateFns.compareAsc) const [workerFn, {status: workerStatus, kill: workerTerminate }] = useWorker(fn, { timeout: 50000 // 5 seconds remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js" // dateFns ], }); ``` -------------------------------- ### Install @koale/useworker with npm Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/installation.md Install the package from npm using the --save flag to add it to dependencies. ```bash npm install --save @koale/useworker ``` -------------------------------- ### Using useWorker: index.js Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/introduction.md Shows the simpler useWorker hook pattern: define a pure function, get a worker instance from the hook, and await the result of calling it with arguments. The worker handles sorting without blocking the UI. ```javascript const sortNumbers = numbers => ([...numbers].sort()) const [sortWorker] = useWorker(sortNumbers); const result = await sortWorker([1,2,3]) ``` -------------------------------- ### Install pnpm globally Source: https://github.com/alewin/useworker/blob/master/docs/CONTRIBUTE.md Install pnpm package manager globally using npm. ```bash npm install -g pnpm ``` -------------------------------- ### Run useWorker development server Source: https://github.com/alewin/useworker/blob/master/docs/CONTRIBUTE.md Start the development server for the useWorker package. ```bash pnpm run dev ``` -------------------------------- ### Import useWorker and WORKER_STATUS Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/installation.md Import the useWorker hook and WORKER_STATUS constant from the package. ```jsx import { useWorker, WORKER_STATUS } from "@koale/useworker"; ``` -------------------------------- ### Bubble Sort with useWorker Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/examples/sort.md Example from the Sorting Numbers documentation page. Imports a bubbleSort algorithm and uses the useWorker hook to sort an array of 50,000 random numbers in a web worker. The result is logged and a success toast is shown on completion. ```javascript import bubbleSort from "./algorithms/bublesort"; const numbers = [...Array(50000)].map(() => Math.floor(Math.random() * 1000000) ); function App() { const [sortWorker, { status: sortWorkerStatus, kill: killWorker }] = useWorker(bubbleSort); const onWorkerSortClick = () => { sortWorker(numbers).then(result => { console.log("Bubble Sort useWorker()", result); addToast("Finished: Sort using useWorker.", { appearance: "success" }); }); }; } ``` -------------------------------- ### Web Worker without useWorker: index.js Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/introduction.md Creates a Worker from webworker.js, posts an array to it, and logs the sorted result from the worker's message event. This is the main-thread counterpart to the webworker.js example. ```javascript var webworker = new Worker("./webworker.js"); webworker.postMessage([3,2,1]); webworker.addEventListener("message", function(event) { console.log("Message from worker:", event.data); // [1,2,3] }); ``` -------------------------------- ### Example: Sorting 5000000 numbers without blocking UI Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/usage.md This example uses useWorker to sort 5000000 numbers in a web worker, keeping the UI responsive. The worker function is called with await and returns a promise. ```javascript import React from "react"; import { useWorker } from "@koale/useworker"; const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000)); const sortNumbers = nums => nums.sort(); const Example = () => { const [sortWorker] = useWorker(sortNumbers); const runSort = async () => { const result = await sortWorker(numbers); // non-blocking UI console.log("End."); }; return ( ); }; ``` -------------------------------- ### useWorker with remoteDependencies for date-fns Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/examples/external.md Sorts dates using date-fns loaded as a remote dependency. The worker has a 5000ms timeout and logs the result, showing a success toast on completion. ```javascript const sortDates = (dates) => { return dates.sort(dateFns.compareAsc); }; const [sortWorker, { status: sortWorkerStatus, kill: killWorker }] = useWorker( sortDates, { timeout: 5000, remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js", ], } ); const onWorkerSortClick = () => { sortWorker(dates).then((result) => { console.log("Bubble Sort useWorker()", result); addToast("Finished: Sort using useWorker.", { appearance: "success" }); }); }; ``` -------------------------------- ### Csv parsing with useWorker Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/examples/csv.md Uses useWorker to run CSV generation and parsing in a worker. The generateWorker produces a fake CSV, then csvWorker parses it and logs the result. Requires the parser modules csvToJson and generateCsv. ```javascript import csvToJson from "./parser/csvToJson"; import generateCsv from "./parser/generateCsv"; function App() { const [generateWorker] = useWorker(generateCsv); const [csvWorker, {status: csvWorkerStatus, kill: killWorker }] = useWorker(csvToJson); const onWorkerCsvClick = async () => { const fakeCsv = await generateWorker(); csvWorker(fakeCsv).then(result => { console.log("Csv useWorker()", result); addToast("Finished: Csv parsed using useWorker()", { appearance: "success" }); }); }; } ``` -------------------------------- ### Basic useWorker example with sorting Source: https://github.com/alewin/useworker/blob/master/README.md A complete React component that uses the useWorker hook to run a sorting function in a Web Worker, keeping the UI responsive. The worker is invoked with the numbers array and returns a promise; the result is logged to the console. ```jsx import React from "react"; import { useWorker } from "@koale/useworker"; const numbers = [...Array(5000000)].map((e) => ~~(Math.random() * 1000000)); const sortNumbers = (nums) => nums.sort(); const Example = () => { const [sortWorker] = useWorker(sortNumbers); const runSort = async () => { const result = await sortWorker(numbers); // non-blocking UI console.log(result); }; return ( ); }; ``` -------------------------------- ### Basic usage of useWorker hook Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/useworker.md Call the useWorker hook with a function and options to get a worker function and controller. ```javascript const [workerFn, controller] = useWorker(fn, options); ``` -------------------------------- ### Web Worker without useWorker: webworker.js Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/introduction.md Plain JavaScript Web Worker that listens for a message, sorts the received array of numbers, and posts the sorted result back. Used to show the verbose event-message pattern that useWorker replaces. ```javascript self.addEventListener("message", function(event) { var numbers = [...event.data] postMessage(numbers.sort()) }); ``` -------------------------------- ### Import useWorker from @koale/useworker Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/usage.md Import the useWorker hook from the package. ```javascript import { useWorker } from "@koale/useworker"; ``` -------------------------------- ### Options API Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/useworker.md The options object passed to useWorker allows configuration of timeout, remote dependencies, auto-termination, and transferable objects. ```APIDOC ## Options API ### Description The options object passed to useWorker allows configuration of timeout, remote dependencies, auto-termination, and transferable objects. ### Parameters - **timeout** (Number) - Optional - The number of milliseconds before killing the worker - **remoteDependencies** (Array of String) - Optional - An array that contains the remote dependencies needed to run the worker - **autoTerminate** (Boolean) - Optional - Kill the worker once it's done (success or error) - **transferable** (String) - Optional - Enable Transferable Objects, to disable it set transferable: 'none' ### Request Example ```javascript import { useWorker } from "@koale/useworker"; const fn = dates => dates.sort(dateFns.compareAsc) const [workerFn, {status: workerStatus, kill: workerTerminate }] = useWorker(fn, { timeout: 50000 // 5 seconds remoteDependencies: [ "https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js" // dateFns ], }); ``` ``` -------------------------------- ### useWorker(fn, options) Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/useworker.md The useWorker hook creates a web worker from a pure function and returns a worker function and a controller. The worker function runs the provided function in a separate thread, and the controller provides status and kill methods. ```APIDOC ## useWorker(fn, options) ### Description The useWorker hook creates a web worker from a pure function and returns a worker function and a controller. The worker function runs the provided function in a separate thread, and the controller provides status and kill methods. ### Parameters - **fn** (Function) - Required - The `pure function` to run with web workers - **options** (Object) - Optional - The object containing the options of the worker ### Returns - **workerFn** (Promise) - The `function` that allows you to run `fn` with web worker - **controller** (Object) - Hook controller (see Controller API) ### Request Example ```javascript import { useWorker } from "@koale/useworker"; const [workerFn, controller] = useWorker(fn, options); ``` ``` -------------------------------- ### Check available CPU cores with navigator.hardwareConcurrency Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/limitation.md Web workers are limited by available CPU and memory. Use navigator.hardwareConcurrency to determine the number of available CPU cores. ```javascript navigator.hardwareConcurrency ``` -------------------------------- ### useWorker returns worker function, status, and kill Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/usage.md useWorker returns an array with the worker function, status, and kill function. The status is defined by WORKER_STATUS constants. ```javascript const sortNumbers = numbers => ([...numbers].sort()) const [sortWorker, { status: sortStatus, kill: killSortWorker }] = useWorker(sortNumbers); ``` -------------------------------- ### Workaround for transpiling issues: wrap function in new Function Source: https://github.com/alewin/useworker/blob/master/README.md Use this workaround when transpiling tools like Babel cause 'Not referenced' errors. Wrapping the function declaration inside a function object as a string avoids scope issues when the function is moved to a worker. ```javascript const sum = new Function(`a`, `b`, `return a + b`); ``` -------------------------------- ### Controller API Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/useworker.md The controller object returned by useWorker provides the status of the worker function and a kill method to terminate the worker. ```APIDOC ## Controller API ### Description The controller object returned by useWorker provides the status of the worker function and a kill method to terminate the worker. ### Properties - **status** (`@WORKER_STATUS`) - The status of `workerFn` - **kill** (Function) - The function that allows killing the worker ``` -------------------------------- ### Web Worker cannot access document or window Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/limitation.md Web workers do not have access to the document or window objects. Attempting to use them will fail. ```javascript document.querySelectorAll('#demoId'); // not allowed!! window.navigator // not allowed!! ``` -------------------------------- ### Cannot call worker while running - create multiple instances Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/limitation.md While a worker is running, you cannot call it again until it finishes or is terminated. To work around this, create multiple instances of the hook. ```javascript const [sort1] = useWorker(sort, { timeout: 10000 }); const [sort2] = useWorker(sort, { autoTerminate: false }); const [sort3] = useWorker(sort); ``` -------------------------------- ### Web Worker cannot return a function Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/limitation.md The web worker cannot return a function because the response is serialized. Returning a function is not allowed; returning a value is allowed. ```javascript const fn = () => { return () => 1 + 2 // not allowed!! } const fn = () => { const sum = 1 + 2 return sum; // allowed!! } ``` -------------------------------- ### Import WORKER_STATUS from @koale/useworker Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/workerstatus.md Import the WORKER_STATUS constant from the @koale/useworker package to access worker status values. ```jsx import { WORKER_STATUS } from "@koale/useworker"; ``` -------------------------------- ### WORKER_STATUS Source: https://github.com/alewin/useworker/blob/master/apps/website/docs/workerstatus.md An enum-like object that provides status constants for the web worker lifecycle. Use these constants to check the current status of a worker returned by the useWorker hook. ```APIDOC ## WORKER_STATUS ### Description An object that provides status constants for the web worker lifecycle. Use these constants to check the current status of a worker returned by the useWorker hook. ### Import ```jsx import { WORKER_STATUS } from "@koale/useworker"; ``` ### Constants - **PENDING** (string) - The web worker has been initialized, but has not yet been executed. - **SUCCESS** (string) - The web worker has been executed correctly. - **RUNNING** (string) - The web worker is running. - **ERROR** (string) - The web worker ended with an error. - **TIMEOUT_EXPIRED** (string) - The web worker was killed because the defined timeout expired. - **KILLED** (string) - The web worker was killed by the kill function. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.