Developer Cheatsheets
react-performance-debugging
Offloading to Web Workers

Advanced Techniques: Improving Performance with Web Workers in TypeScript & React

Hello seasoned React developers! You've likely encountered scenarios where computational heavy lifting causes your React app to lag, much like an overburdened accountant during tax season. Web Workers can provide much-needed relief. They offload tasks, ensuring your main thread remains free and responsive.

Problem - Main Thread Overload

Overloading the main thread with excessive computations can lead to a sluggish, unresponsive user interface (UI). This is far from ideal.

Consider this example where we have a function findBestDeal in our e-commerce app. This function performs complex calculations across a list of products to identify the best deal.

BestDeal.tsx

import React from "react";
 
const findBestDeal = (products: Array<Product>) => {
  // Complex computations...
};
 
const BestDeal = ({ products }: { products: Array<Product> }) => {
  const bestDeal = findBestDeal(products);
 
  return <div>Best deal: {bestDeal.name}</div>;
};
 
export default BestDeal;

Solution - Web Workers

Web Workers can handle these intensive tasks, allowing the main thread to focus on user interactions. Let's create a worker that will compute the best deal.

bestDealWorker.ts

self.onmessage = (event) => {
  const products = event.data;
  // Compute the best deal here...
 
  self.postMessage(bestDeal);
};

Integrating Web Workers with React

We can now integrate our newly minted worker within the BestDeal component.

BestDeal.tsx

import React, { useEffect, useState } from "react";
import Worker from "./bestDealWorker";
 
const BestDeal = ({ products }: { products: Array<Product> }) => {
  const [bestDeal, setBestDeal] = useState<Product | null>(null);
  const worker = new Worker();
 
  useEffect(() => {
    worker.postMessage(products);
    worker.onmessage = (event) => setBestDeal(event.data);
    return () => worker.terminate();
  }, [products]);
 
  return <div>Best deal: {bestDeal ? bestDeal.name : "Calculating..."}</div>;
};
 
export default BestDeal;

Summary

Utilizing Web Workers, we've successfully delegated intensive tasks, keeping our main thread unencumbered and responsive. It's important to note that while Web Workers enhance performance in certain scenarios, they are not universally applicable and introduce their own complexity. For instance, they cannot access the DOM. However, in the case of heavy computations, they are undoubtedly a valuable tool in your optimization toolbox. Congratulations, you're effectively harnessing the power of Web Workers!