首页 > web前端 > js教程 > 正文

什么是 Web Worker 以及如何在 NextJS 中使用它

WBOY
发布: 2024-09-12 10:33:50
原创
238 人浏览过

What is Web worker and how to use it in NextJS

Prerequisite

  • Basic knowledge of ReactJS/NextJS

What is Web Worker

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


Why create other threads when you can just work on the main thread?

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


How to use Web Worker in NextJS

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

  • Init you NextJS project as usual
  • Make the page.tsx a client component by add 'use client' on top of the file because we want to use react hooks here for this sample
  • Create an input with the usual value state and onChange handler
  • Create a button with an onClick event we going to use this button to tell web worker to fetch the API
  • Create a Ref to hold the web worker instance
  • Create an Effect to initialize the web worker and attach an event to handle the data web worker sends back with and terminate the thread/web worker after the page unmounted
  • Create a state to hold image urls receives from the web worker.
  • page.tsx looks like this
"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>
    );
}
登录后复制
  • Create A file called worker.ts in the same folder as page.tsx
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!

以上是什么是 Web Worker 以及如何在 NextJS 中使用它的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!