Home >Web Front-end >JS Tutorial >What is Web worker and how to use it in NextJS
JavaScript is a single-threaded language, the thread it uses is referred as the main thread
Brower in fact use other threads
Web worker from browser API is a way for you to create and register additional threads with JavaScript
Let says you need to compute a lot of data to draw a chart.
Those computation could take long enough to make the page unresponsive
That's where web worker comes in.
You can create new thread to compute those data and when its done, web worker can send back the result to the main thread
In this sample I'm going to use Web Worker to fetch dog pictures API and send back the result to the main thread to display those images
"use client"; import { ChangeEvent, MouseEvent, useCallback, useEffect, useRef, useState } from "react"; export default function Home() { const [userInput, setUserInput] = useState<string>(""); const workerRef = useRef<Worker>(); const [dogPics, setDogPics] = useState<string[]>(); useEffect(() => { workerRef.current = new Worker(new URL("./worker.ts", import.meta.url)); workerRef.current.onmessage = (event: MessageEvent<string[]>) => setDogPics(event.data); return () => { workerRef.current?.terminate(); }; }, []); const handleUserInputChange = useCallback( (e: ChangeEvent<HTMLInputElement>) => { setUserInput(e.target.value); }, [setUserInput] ); const handleFetch = useCallback( (e: MouseEvent<HTMLButtonElement>) => { userInput && workerRef.current?.postMessage(userInput); }, [userInput] ); return ( <div> <input placeholder="number of dogs" value={userInput} onChange={handleUserInputChange} className="mr-4 text-black" ></input> <button className="bg-green-500 text-black rounded" onClick={handleFetch}> fetch </button> {dogPics && dogPics.map((pic) => <img key={pic} src={pic} alt="dog pic"></img>)} </div> ); }
self.onmessage = async (e: MessageEvent<string>) => { const url = `https://dog.ceo/api/breeds/image/random/${e.data}`; const response = await fetch(url).then((res) => res.json()); self.postMessage(response.message); };
Now run you app and check the result!
The above is the detailed content of What is Web worker and how to use it in NextJS. For more information, please follow other related articles on the PHP Chinese website!