Created
May 16, 2023 13:41
-
-
Save TheRakeshPurohit/6031d55eab874fb45c3b5216f549f552 to your computer and use it in GitHub Desktop.
Simplifying web worker as a React hook
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 { useState, useEffect } from 'react'; | |
function useWebWorker(workerFunction) { | |
const [result, setResult] = useState(null); | |
useEffect(() => { | |
const worker = new Worker('worker.js', { credentials: "same-origin", name: "justCheking", type: "module" }); | |
const handleMessage = (event) => { | |
const { data } = event; | |
setResult(data); | |
}; | |
worker.addEventListener('message', handleMessage); | |
const executeFunction = () => { | |
worker.postMessage({ function: workerFunction.toString(), args: [] }); | |
}; | |
executeFunction(); | |
return () => { | |
worker.removeEventListener('message', handleMessage); | |
worker.terminate(); | |
}; | |
}, []); | |
return result; | |
} | |
export default useWebWorker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment