Ever clicked a button in a web app, and the UI just froze? Maybe a timer stopped, animations stuttered, or clickable elements stopped responding. This happens because JavaScript is single-threaded, meaning it can only do one thing at a time.
When a heavy computation runs on the main thread, it blocks the UI, creating a poor user experience.
In this blog, we’ll explore Web Workers, a simple and effective way to offload heavy computations to a background thread in a React app, keeping your UI smooth and responsive.
Understanding the problem: single-threaded JavaScript
JavaScript runs on a single thread that handles both:
This means if you run a heavy task, everything else stops until it finishes. Here’s a classic example:
If this runs on the main thread, timers, animations, and clicks stop responding.
Introducing web workers
Web Workers allow us to run JavaScript code in a separate background thread. This way:
Note: Workers cannot access the DOM directly; they are only for computations.
Web worker syntax
Worker File (public/worker.js):
Main Thread (React Component):
React demo: without vs with web worker
Setting up a Next.js Project with Web Workers
1. Create Next.js App
2. Project Folder Structure
Here’s a minimal structure we’ll use:
Without worker (UI freezes)
Create WithoutWorker Component File (app/WithoutWorker.js)
Observation: Click the box while running the heavy task , nothing happens. The timer also freezes.
With worker (UI smooth)
Create Worker File (public/worker.js)
Create WithWorker Component File (app/WithWorker.js)
Observation: Click the box while the worker runs, the timer keeps going, and the box responds instantly!
Error handling
Handle Worker Errors in React
You can attach an onerror listener when creating the worker:
Catch Errors Inside Worker File
In your worker.js, wrap computation in a try/catch:
Key takeaways
Conclusion
Web Workers keep React apps responsive by moving heavy computations off the main thread, ensuring smooth user experiences even under load. They are already valuable in finance, simulations, and real-time communication, and their role will expand as WebAssembly, progressive web apps, and edge computing mature.
Countries like Singapore, South Korea, and Estonia are leading in digital infrastructure, while global research explores energy-efficient and privacy-focused applications. Future directions include integration with in-browser AI, distributed multi-worker systems, and secure collaboration protocols.
In my view, Web Workers are still underused in React, but they are on track to become a standard tool for performance-driven development.