Last active
December 14, 2022 18:36
-
-
Save mike-at-redspace/dfcc81fc711814f42a9cc3dba7a7ab52 to your computer and use it in GitHub Desktop.
React Worker Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react' | |
const useWebWorker = (workerUrl, callback) => { | |
const [worker, setWorker] = useState(null) | |
useEffect(() => { | |
if (workerUrl) { | |
const newWorker = new Worker(workerUrl) | |
setWorker(newWorker) | |
} | |
return () => { | |
if (worker) { | |
worker.terminate() | |
} | |
} | |
}, [workerUrl]) | |
useEffect(() => { | |
if (worker) { | |
worker.addEventListener('message', event => { | |
callback(event.data) | |
}) | |
} | |
}, [worker]) | |
return worker | |
} | |
export default MyComponent = () => { | |
const handleWorkerMessage = data => { | |
console.log(data) | |
} | |
const worker = useWebWorker('/my-worker.js', handleWorkerMessage) | |
useEffect(() => { | |
if (worker) { | |
worker.postMessage('hello from the main thread!') | |
} | |
}, [worker]) | |
return <div>My component</div> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment