### Install useworker via npm
Source: https://useworker.js.org/docs/installation
Use this command to install the latest version of the @koale/useworker package as a dependency.
```bash
npm install --save @koale/useworker
```
--------------------------------
### Web Worker: hardwareConcurrency - determining number of CPU cores
Source: https://useworker.js.org/docs/limitations
Web Workers are limited by CPU and memory, and this example shows how to determine the available CPU cores using the navigator.hardwareConcurrency property.
```javascript
navigator.hardwareConcurrency
```
--------------------------------
### Bubble Sort with useWorker
Source: https://useworker.js.org/docs/examples/examples-sort
This example shows how to import a bubble sort algorithm and execute it asynchronously using the useWorker hook within a React component.
```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" });
});
};
}
```
--------------------------------
### useWorker options example with remote dependency
Source: https://useworker.js.org/docs/api-useworker
Example of using useWorker with a timeout of 50000 milliseconds and a remote dependency for date-fns. The worker function sorts dates using dateFns.compareAsc.
```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
],
});
```
--------------------------------
### Implement useWorker for non-blocking sorting
Source: https://useworker.js.org
This example demonstrates how to use the useWorker hook to sort a large array of numbers in a background thread, keeping the UI responsive.
```javascript
import React from "react";
import { useWorker, WORKER_STATUS } from "@koale/useworker";
const numbers = [...Array(5000000)].map(e => ~~(Math.random() * 1000000));
const sortNumbers = nums => nums.sort();
const Example = () => {
const [sortWorker, { status, kill }] = useWorker(sortNumbers);
const runSort = async () => {
const result = await sortWorker(numbers); // non-blocking UI
console.log("End.");
};
return ();
};
```
--------------------------------
### Web Worker: No document or window access - not allowed (LIMITATION: 1)
Source: https://useworker.js.org/docs/limitations
Workers lack access to the document and window objects. Attempting to use these APIs will fail. This example shows two disallowed calls.
```javascript
document.querySelectorAll('#demoId'); // not allowed!!
window.navigator // not allowed!!
```
--------------------------------
### index.js: Using useWorker to sort numbers
Source: https://useworker.js.org/docs/introduction
Defines a sort function and uses useWorker() to get a worker that can be invoked with await to sort array [1,2,3].
```javascript
const sortNumbers = numbers => ([...numbers].sort())
const [sortWorker] = useWorker(sortNumbers);
const result = await sortWorker([1,2,3])
```
--------------------------------
### Sort 5 million numbers with useWorker
Source: https://useworker.js.org/docs/usage
Complete example sorting 5,000,000 numbers in a web worker without blocking the UI. The worker is invoked with await and logs "End." after completion.
```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 (
);
};
```
--------------------------------
### Web Worker: Multiple useWorker instances to avoid re-call while running
Source: https://useworker.js.org/docs/limitations
The web worker cannot be invoked again while running unless it is finished or killed. Creating multiple instances with the hook overcomes this. The example defines three separate useWorker calls with different configurations.
```javascript
const [sort1] = useWorker(sort, { timeout: 10000 });
const [sort2] = useWorker(sort, { autoTerminate: false });
const [sort3] = useWorker(sort);
```
--------------------------------
### Web Worker: Return function is not allowed but return sum is allowed
Source: https://useworker.js.org/docs/limitations
Workers cannot return a function because responses are serialized. Only serializable data such as numbers or sums can be returned. The example contrasts the disallowed function return with the allowed sum return.
```javascript
const fn = () => {
return () => 1 + 2 // not allowed!!
}
const fn = () => {
const sum = 1 + 2
return sum; // allowed!!
}
```
--------------------------------
### index.js: Create and communicate with a raw Web Worker
Source: https://useworker.js.org/docs/introduction
Main script that instantiates a new Worker from './webworker.js', sends an array [3,2,1], and listens for the sorted response, logging [1,2,3].
```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]
});
```
--------------------------------
### CSV parsing with useWorker
Source: https://useworker.js.org/docs/examples/examples-csv
Demonstrates initializing workers for CSV generation and parsing, and handling the asynchronous result of the parsing operation.
```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"
});
});
};
}
```
--------------------------------
### Import useWorker from @koale/useworker
Source: https://useworker.js.org/docs/api-useworker
Import the useWorker hook from the @koale/useworker package.
```javascript
import { useWorker } from "@koale/useworker";
```
--------------------------------
### Import useworker components
Source: https://useworker.js.org/docs/installation
Import the useWorker hook and WORKER_STATUS constant from the package.
```javascript
import { useWorker, WORKER_STATUS } from "@koale/useworker";
```
--------------------------------
### useWorker(fn, options)
Source: https://useworker.js.org/docs/api-useworker
The useWorker hook takes a pure function and optional options, and returns a worker function and a controller object. The worker function runs the provided function in a web worker, 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 web worker, and the controller provides status and kill methods.
### Import
```
import { useWorker } from "@koale/useworker";
```
### Usage
```
const [workerFn, controller] = useWorker(fn, options);
```
### 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).
### Options
- **timeout** (Number) - Default: undefined - The number of milliseconds before killing the worker.
- **remoteDependencies** (Array of String) - Default: [] - An array that contains the remote dependencies needed to run the worker.
- **autoTerminate** (Boolean) - Default: true - Kill the worker once it's done (success or error).
- **transferable** (String) - Default: 'auto' - Enable Transferable Objects, to disable it set transferable: 'none'.
### Example
```
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
],
});
```
```
--------------------------------
### Call useWorker with a sorting function
Source: https://useworker.js.org/docs/usage
useWorker returns an array with the worker function, a status object (using WORKER_STATUS constants), and a kill function to terminate the worker.
```javascript
const sortNumbers = numbers => ([...numbers].sort())
const [sortWorker, { status: sortStatus, kill: killSortWorker }] = useWorker(sortNumbers);
```
--------------------------------
### Controller API
Source: https://useworker.js.org/docs/api-useworker
The controller object returned by useWorker provides the status of the worker function and a kill function to terminate the worker.
```APIDOC
## Controller API
### Description
The controller object returned by useWorker provides the status of the worker function and a kill function to terminate the worker.
### Properties
- **status** (@WORKER_STATUS) - The status of `workerFn`.
- **kill** (Function) - The function that allows killing the worker.
```
--------------------------------
### Import WORKER_STATUS
Source: https://useworker.js.org/docs/api-workerstatus
Import the WORKER_STATUS constants from the @koale/useworker package to track the lifecycle of a web worker.
```javascript
import { WORKER_STATUS } from "@koale/useworker";
```
--------------------------------
### useWorker hook usage signature
Source: https://useworker.js.org/docs/api-useworker
Shows the destructured return values: workerFn and controller, obtained by calling useWorker with a function and options.
```javascript
const [workerFn, controller] = useWorker(fn, options);
```
--------------------------------
### Sort Dates with useWorker and date-fns Remote Dependency
Source: https://useworker.js.org/docs/examples/examples-external
Sorts a dates array using date-fns compareAsc inside a Web Worker via the useWorker hook. It specifies a 5000ms timeout and the remote dependency URL for date-fns, then asynchronously processes the sort and displays a success toast.
```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" });
});
};
```
--------------------------------
### webworker.js: Message event listener for sorting numbers
Source: https://useworker.js.org/docs/introduction
A minimal Web Worker that receives an array of numbers via a message event, copies it, sorts it, and posts the sorted array back.
```javascript
self.addEventListener("message", function(event) {
var numbers = [...event.data]
postMessage(numbers.sort())
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.