How to handle CPU-intensive tasks

Web workers make the application fast by running CPU-intensive tasks on a different thread other than the main thread.

Sorting, search, graph traversal, matrix multiply are all CPU operations, a process is CPU-intensive or not it depends on how much and how frequent are their execution.

Web Workersarrow-up-right are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.

circle-info

Run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.

Workerize-loaderarrow-up-right - a webpack loader that moves a module and its dependencies into a Web Worker, automatically reflecting exported functions as asynchronous proxies.

npm install -D workerize-loader
import {getItems} from '../workerized-expensive'

workerized-expensive.js

import makeItemsWorker from 'workerize!./expensive'

const {getItems} = makeItemsWorker()

export {getItems}

expensive.js is our function that may slow down an application.

circle-exclamation

import React from 'react'
import {getItems} from '../workerized-expensive'
import {useAsync} from '../utils'


  const {data: allItems, run} = useAsync({data: [], status: 'pending'})
  React.useEffect(() => {
    run(getItems(inputValue))
  }, [inputValue, run])
  
  const items = allItems.slice()

Because working with web workers is asynchronous, you'll probably want to use the useAsync

Last updated