Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda