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

96
Visualizações
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 à 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