"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is Web worker and how to use it in NextJS

What is Web worker and how to use it in NextJS

Published on 2024-11-02
Browse:595

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("");
    const workerRef = useRef();
    const [dogPics, setDogPics] = useState();

    useEffect(() => {
        workerRef.current = new Worker(new URL("./worker.ts", import.meta.url));
        workerRef.current.onmessage = (event: MessageEvent) => setDogPics(event.data);
        return () => {
            workerRef.current?.terminate();
        };
    }, []);

    const handleUserInputChange = useCallback(
        (e: ChangeEvent) => {
            setUserInput(e.target.value);
        },
        [setUserInput]
    );

    const handleFetch = useCallback(
        (e: MouseEvent) => {
            userInput && workerRef.current?.postMessage(userInput);
        },
        [userInput]
    );

    return (
        
                                    {dogPics && dogPics.map((pic) => dog pic)}        
    ); }
  • Create A file called worker.ts in the same folder as page.tsx
self.onmessage = async (e: MessageEvent) => {
    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!

Release Statement This article is reproduced at: https://dev.to/theteabagcoder/what-is-web-worker-and-how-to-use-it-in-nextjs-4ndm?1 If there is any infringement, please contact [email protected] delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3