Last active
November 17, 2024 18:36
-
-
Save Dissolutio/63de7d7473c1424db5c896d73ad6dc3c to your computer and use it in GitHub Desktop.
Example of a React component in a Vite app that uses a WebWorker in a useEffect (example worker file included) (SUPER SIMPLE, NO LIBRARIES!)
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 from 'react' | |
| type WorkerArgs = { | |
| some: string | |
| } | |
| /* myCoolWorker.js | |
| // because we specify {type: 'module} in worker options, we can import from our project! | |
| import { coolFn } from './someDir/coolFn' | |
| self.onmessage = (event) => { | |
| const workerArgs = event?.data | |
| const result = coolFn?.(workerArgs) ?? workerArgs // if you don't have a coolFn, borrow mine | |
| self.postMessage(result) | |
| } | |
| */ | |
| const WorkerExample = () => { | |
| const [state, setState] = React.useState('') | |
| const workerRef = React.useRef<Worker>(); | |
| // effect: start/terminate worker, set up what to do with its return | |
| React.useEffect(() => { | |
| const worker = new Worker(new URL('./myCoolWorker.js', import.meta.url), { type: 'module' }); // | |
| workerRef.current = worker | |
| workerRef.current.onmessage = (event) => { | |
| const workerData = event.data | |
| setState(workerData) | |
| }; | |
| return () => { | |
| workerRef.current.terminate(); | |
| }; | |
| }, []); | |
| function runWorker(workerArgs: WorkerArgs) { | |
| workerRef?.current?.postMessage?.(workerArgs); | |
| } | |
| const shouldUseWorker = true // in reality this will be some dynamic reason/thing | |
| // effect: use worker to calculate something | |
| React.useEffect(() => { | |
| if (shouldUseWorker) { | |
| const workerArgs = { | |
| some: 'stuff' | |
| } | |
| runWorker(workerArgs); | |
| } | |
| }, [shouldUseWorker]) | |
| return ( | |
| <div>WorkerExample</div> | |
| ) | |
| } | |
| export default WorkerExample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment