@runstack/hooks
v0.4.0
Published
React hooks library for runstack
Downloads
14
Maintainers
Readme
@runstack/hooks
A collection of React hooks for runstack projects.
Installation
npm install @runstack/hooksUsage
import { useWorker } from '@runstack/hooks';
function MyComponent() {
const { worker, send } = useWorker({
createWorker: () => new Worker('/path/to/worker.js'),
onMessage: (event) => {
console.log('Received from worker:', event.data);
},
});
const handleSendMessage = () => {
send({ type: 'PROCESS_DATA', payload: 'some data' });
};
return (
<div>
<button onClick={handleSendMessage}>
Send Message to Worker
</button>
</div>
);
}Available Hooks
useWorker<TPostMessageType, TWorkerMessage>(options)
Provides a simple interface for working with Web Workers.
Parameters:
- options: Configuration object
- createWorker:
() => Worker- Function that creates and returns a Worker instance - onMessage:
(message: MessageEvent<TWorkerMessage>) => void- Callback for handling messages from the worker
- createWorker:
Returns: { worker: Worker, send: (message: TPostMessageType) => void }
- worker: The Worker instance
- send: Function to send messages to the worker
TypeScript Support:
- TPostMessageType: Type of messages sent to the worker
- TWorkerMessage: Type of messages received from the worker (defaults to TPostMessageType)
Example with TypeScript:
type WorkerInput = { type: 'CALCULATE'; numbers: number[] };
type WorkerOutput = { type: 'RESULT'; result: number };
const { worker, send } = useWorker<WorkerInput, WorkerOutput>({
createWorker: () => new Worker('/calculator-worker.js'),
onMessage: (event) => {
if (event.data.type === 'RESULT') {
console.log('Calculation result:', event.data.result);
}
},
});
send({ type: 'CALCULATE', numbers: [1, 2, 3, 4, 5] });Development
# Build the package
npm run build
# Watch for changes during development
npm run dev
# Run linting
npm run lint
# Type checking
npm run check-typesLicense
MIT
