javascript / expert
Snippet
Off-Main-Thread Computation Hook
For heavy computations (e.g., image processing or complex data filtering), offloading work to a Web Worker is crucial to keep the main UI thread responsive. This hook encapsulates the worker lifecycle within React's effect system.
snippet.js
1
2
3
4
5
6
7
8
9
10
function useWorker(workerScript, inputData) {const [result, setResult] = useState(null);useEffect(() => {const worker = new Worker(workerScript);worker.postMessage(inputData);worker.onmessage = (e) => setResult(e.data);return () => worker.terminate();}, [workerScript, JSON.stringify(inputData)]);return result;}
react
Breakdown
1
const worker = new Worker(workerScript);
Initializes a new background thread for heavy processing.
2
return () => worker.terminate();
Cleanup function to prevent memory leaks by terminating the worker when the component unmounts.