Can we set state of react component in worker thread?

Viewed 302

In react / nextjs can we set State of functional component from inside worker thread. for example

//main.ts
export function myComponent (){
 const [user ,setUserDetails] = useState(false)
 const [profile ,setProfile] = useState(false)
....

  useEffect( () => {
   worker = new Worker('my.ts');
   worker.postMessage([user,profile,setUserDetails,setProfile])
  },[])
}

and then in worker thread

/* my.js* /

self.onmessage = (data)=>{

    //long task
    users = getUSers();

   // this valid?
   data.setUserDetails(user);

   // continue process 
   profile = getProfile();

  data.setProfile(profile);

//and so on

}

Is this possible as we can't directly update dom in worker but I think react uses virtual dom.So it could still be possible.If not what is work around for this?

1 Answers

Yes, this is possible. An easy way to achieve this is to use callbacks in Comlink. For instance, in your worker.js you can

import * as Comlink from "comlink";

async function longTask(callback) {
  // get your users 
  await callback(users);
}

Comlink.expose(longTask);

and in your component you can:

import * as Comlink from "comlink";
import Worker from "worker-loader!./Worker.js";

const longTask = Comlink.wrap(new Worker());

const Component = () => {

    const [users, setUsers] = useState(null);

    const callback = (value) => {
        setUsers(value);
    };

    const onSomeEvent = async () => {
        await longTask(Comlink.proxy(callback));
    };
 
    // ...
Related