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

98
Vistas
Use React Hooks in class object

I know it is not possible to use Hooks in Class Components, that is not what I am trying to achieve.

I have a Context I want to access in a service class.

/* File MyComponent.tsx */
function MyComponent() {
  MyService.foo();
  return (
    <h1>Anything</h1>
  )
}

/* File MyService.tsx */
class MyService {
 foo() {
   const [dispatch] = React.useContext(MyContext);
   dispatch({type: 'myaction'});
 }
}
export default new MyService()

I Have already found a workaround by passing the dispatch callback from the component to the service method. But this is pretty ugly and tedious.

function useMyServiceFoo(params) {
  const [dispatch] = React.useContext(MyContext);
  MyService.foo(dispatch, params);
}

As this is working I wonder why it is not when I call useContext in the class methods ? Is there a way I can make it works ?

about 4 years ago · Juan Pablo Isaza
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