Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Hooks and webworkers

Is there a way for a webworker to use a react hook?

I am using Apollo Client to perform useLazyQuery which is a custom hook.

But the actual operation takes quite long and times out most often!

I want to run this on another thread to not disrupt the main application.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Although I'm not sure whether your timeout problem would be fixed by executing the query in a webworker, the easiest way to achieve that (without considering pending/error states) would be something like this:

worker.js

self.addEventListener('message', async event => {
  const {apolloClient, query} = e.data;
  const result = await apolloClient.query({query});  
  self.postMessage(result);
  self.close();
});
App.jsx

const query = gql`Some query here`;

const useWebWorkerQuery = query => {
  const apolloClient = useApolloClient();
  const [result, setResult] = useState(null);

  useEffect(() => {
    const worker = new Worker('worker.js');
    worker.postMessage({apolloClient, query});
    worker.onmessage = event => setResult(event.data);
  }, []);
};

const App = () => {
  const result = useWebWorkerQuery(query);

  useEffect(() => {
    if(result) {
      // Do something once query completes
    }
  }, [result]);

  return null;
};

export default App;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!