How to use "vanilla" WebWorker in React?

How do I use webworkers in a react app ?

I wrote an webworker and tested it in a simple app (html) so it works fine.

But using same approach in a react app doesnt work

I don't want at first use any react-something-webworker, I want just use pure Work api

const _worker = new Worker('./worker')

seems not importing the code inside worker.js file (self.addEventListener("message...)

Thanks for helping

Upvotes: 0

Views: 1254

Answers (1)

jackdbd
jackdbd

Reputation: 5061

In a React class component you can instantiate a web worker in componentDidMount, define the worker's onmessage and onerror methods, then call worker.terminate() in componentWillUnmount.

In a React function component, replace componentDidMount and componentWillUnmount with useEffect.

Your React component and your worker can then exchange messages with postMessage.


Even if you don't want to use any React-specific libraries, have a look at the code from the react-hooks-worker library. It's less than 100 LOC and it will help you understand how to use the Web Worker API.

Upvotes: 1

Related Questions