forked from DustinBrett/daedalOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseWorker.ts
More file actions
32 lines (25 loc) · 747 Bytes
/
useWorker.ts
File metadata and controls
32 lines (25 loc) · 747 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useEffect, useRef } from "react";
const useWorker = <T>(
workerInit?: (info?: string) => Worker,
onMessage?: (message: MessageEvent<T>) => void,
workerInfo?: string
): React.RefObject<Worker | undefined> => {
const worker = useRef<Worker>(undefined);
useEffect(() => {
if (workerInit && !worker.current) {
worker.current = workerInit(workerInfo);
if (onMessage) {
worker.current.addEventListener("message", onMessage, {
passive: true,
});
}
worker.current.postMessage("init");
}
return () => {
worker.current?.terminate();
worker.current = undefined;
};
}, [onMessage, workerInfo, workerInit]);
return worker;
};
export default useWorker;