@nexus-state/web-worker
v0.1.6
Published
> Nexus State integration with Web Workers — offload heavy computations > > [](https://www.npmjs.com/package/@nexus-state/web-worker) > [
- Related:
- @nexus-state/async — Simple async state
- @nexus-state/query — Data fetching with caching
Full ecosystem: Nexus State Packages
Description
The @nexus-state/web-worker package provides tools for working with Nexus State in Web Workers.
Installation
npm install @nexus-state/web-workerKey Features
- Offload heavy computations to Web Workers
- Automatic sync of worker state to main thread stores
- Zero-config store tracking with
createWorkerStore()
Quick Start
Main Thread
import { workerAtom, createWorkerStore, ensureWorkerTracking } from '@nexus-state/web-worker';
// Create a Web Worker
const worker = new Worker('./my-worker.js');
// Create a worker-managed atom
const [counterAtom, setCounter] = workerAtom({
worker,
initialValue: 0,
});
// Create a store that tracks worker atoms
const store = createWorkerStore();
// Or use ensureWorkerTracking with an existing store
// import { createStore } from '@nexus-state/core';
// const store = createStore();
// ensureWorkerTracking(store);
// Subscribe to worker atom changes
store.subscribe(counterAtom, (value) => {
console.log('Counter updated:', value);
});
// Get current value
console.log(store.get(counterAtom)); // 0Web Worker (my-worker.js)
// In the worker, handle messages from main thread
self.onmessage = (event) => {
const { type, value } = event.data;
switch (type) {
case 'INCREMENT':
const newValue = value + 1;
// Send updated value back to main thread
self.postMessage({ type: 'UPDATE', value: newValue });
break;
case 'HEAVY_CALCULATION':
const result = performHeavyCalculation(value);
self.postMessage({ type: 'UPDATE', value: result });
break;
}
};Communication Pattern
// Main thread: send message to worker
worker.postMessage({ type: 'INCREMENT', value: store.get(counterAtom) });
// The worker processes and sends back UPDATE
// Main thread automatically syncs via workerAtom trackingLicense
MIT
