Skip to content

How to properly use the Web Worker api? #407

Answered by zhuoqyin
zhuoqyin asked this question in Q&A
Discussion options

You must be logged in to vote

@bm777 Thanks for the suggestion.

For those who still wants to use the Web Worker api from the client side and run into this issue.
I figured that the problem I had is that Next.js tries to pre-render pages on the server side.
You should create the worker in a react effect to guarantee the logic happens in the client side.

  const workerRef = React.useRef<Worker>(null);

  React.useEffect(() => {
    workerRef.current = new Worker("sampleWorker.js");

    workerRef.current.onmessage = (e) => { };

    return () => {
      workerRef.current.terminate(); // Clean up on component unmount
    }}, []);

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by bm777
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants