Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda