Interview frequency: …
Short answer
Use Web Workers to process large datasets and decode files on a separate background thread, keeping the UI smooth and responsive at 60fps.
Explanation
Because JavaScript is Single Threaded, heavy calculations can freeze the UI. A Web Worker runs scripts in the background and communicates with React through postMessage and onmessage. Modern tools such as Comlink make these calls resemble ordinary function calls.
Code example
// Create and use Worker
const worker = new Worker(new URL('./heavy-calc.worker.ts', import.meta.url));
function runCalculation(data: BigData) {
worker.postMessage(data);
worker.onmessage = (e) => {
setResult(e.data);
};
}Common mistakes
- Trying to pass DOM objects or non-serializable functions through postMessage to a Worker.