惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
Jina AI
Jina AI
罗磊的独立博客
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
J
Java Code Geeks
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
InfoQ
月光博客
月光博客
博客园_首页
Vercel News
Vercel News
P
Proofpoint News Feed
GbyAI
GbyAI
Y
Y Combinator Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
ReactJs Performance ~ Web Workers for Heavy Computations ~
Ogasawara Ka · 2026-05-03 · via DEV Community
Cover image for ReactJs Performance ~ Web Workers for Heavy Computations ~

Ogasawara Kakeru

JavaScript runs on a single thread, which means intensive tasks can freeze the UI and hurt the user experience.

To avoid this, you can offload heavy work to background threads using Web Workers.

🔧 When Web Workers are useful

  • Processing images or videos in the browser
  • Handling large datasets (sorting, filtering, transformations)
  • Performing CPU-heavy calculations (e.g. simulations, analytics)
  • Parsing large files like CSV, JSON, or XML
  • Running cryptographic or hashing operations
  • Managing real-time data streams without blocking the UI

Web Worker implementation example

// dataWorker.js
self.addEventListener('message', event => {
  const { items, taskType } = event.data;

  const output = runBackgroundTask(items, taskType);

  self.postMessage({
    status: 'completed',
    result: output,
  });
});

function runBackgroundTask(items, taskType) {
  if (taskType !== 'transform') {
    return items;
  }

  return items.map(item => {
    return applyHeavyTransformation(item);
  });
}

function applyHeavyTransformation(item) {
  // Put CPU-heavy logic here
  return {
    ...item,
    processed: true,
  };
}

Enter fullscreen mode Exit fullscreen mode

// DataProcessor.jsx
import { useEffect, useState } from 'react';

function DataProcessor({ items }) {
  const [result, setResult] = useState([]);
  const [isRunning, setIsRunning] = useState(false);

  useEffect(() => {
    const backgroundWorker = new Worker(
      new URL('./dataWorker.js', import.meta.url)
    );

    backgroundWorker.addEventListener('message', event => {
      setResult(event.data.result);
      setIsRunning(false);
    });

    setIsRunning(true);

    backgroundWorker.postMessage({
      items,
      taskType: 'transform',
    });

    return () => {
      backgroundWorker.terminate();
    };
  }, [items]);

  if (isRunning) {
    return <LoadingIndicator />;
  }

  return <DataVisualization data={result} />;
}

Enter fullscreen mode Exit fullscreen mode

In this example, the expensive transformation is moved outside the main React rendering flow.

The component sends raw data to the worker, waits for the processed result, and keeps the UI responsive while the task runs in the background.

Performance Comparison by Task Type

Task Main Thread Worker Thread UI Smoothness Implementation Difficulty
Image filtering ~800ms (blocks execution) ~850ms (runs off the main thread) Maintains 60 FPS Moderate
Data sorting (100k items) ~450ms (blocking) ~480ms (non-blocking) Maintains 60 FPS Low
JSON parsing (large payload) ~600ms (causes freeze) ~620ms (handled in background) Maintains 60 FPS Low
Physics simulations ~1200ms (UI freeze) ~1250ms (processed asynchronously) Maintains 60 FPS High
Cryptographic operations ~350ms (blocking) ~360ms (keeps UI responsive) Maintains 60 FPS Moderate
Video transcoding Not feasible (too heavy) Executed in background Maintains 60 FPS Very High

⚠️ Things to know before using Web Workers

While Web Workers are powerful, they come with a few trade-offs:

  • They cannot directly interact with the DOM
  • Memory is isolated from the main thread (SharedArrayBuffer is an advanced workaround)
  • Communication between threads introduces latency (~5–10ms per message)
  • Data must be serialized/deserialized when passing between threads

🧠 When should you actually use them?

A good rule of thumb:

If a task takes longer than ~50ms, it's a good candidate for a Web Worker.

For shorter operations, the cost of message passing can outweigh the performance gains.

In those cases, you might be better off using:

  • requestIdleCallback → to run tasks when the browser is idle
  • Simple async patterns → to avoid blocking rendering

🛠️ Modern tooling makes it easier

Today’s tooling significantly reduces the complexity of working with Web Workers:

  • Vite / Webpack → allow direct worker imports with minimal setup
  • Comlink → abstracts message passing into a simple function-call-like API

These tools make it much easier to integrate background processing into modern frontend applications without dealing with low-level boilerplate.


💡 Practical perspective

Use Web Workers selectively.

They shine in CPU-heavy scenarios, but for lightweight tasks, simpler approaches often lead to better overall performance and maintainability.