React - Web Worker

Introduction

Web - Worker

Usage

To solve the UI freezing problem, we can move the heavy calculation to a Web Worker. A Web Worker runs JavaScript code in a separate thread, allowing the main thread to remain free to handle user interactions and UI updates.

In our React component, we create an instance of the worker and communicate with it:

App.tsx
useEffect(() => {
workerRef.current = new Worker(
new URL("./workers/fibWorker.ts", import.meta.url),
{ type: "module" },
);
workerRef.current.onmessage = (e: MessageEvent<Result>) => {
setResults((prev) => [...prev, e.data]);
};
}, []);
const handleClick = () => {
if (workerRef.current) {
workerRef.current.postMessage({ id: idRef.current++, n: 42 });
}
};

Now, when we click the button, the Fibonacci calculation runs in the background, and the UI remains responsive.

Pending