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

241
Visualizações
Is there a way to call useContext in a click callback?

I'm learning React and have a custom Context accessible with a use method:

// In a Provider file.
export const useUsefulObject(): UsefulObject {
  return useContext(...)
}

I want to use UsefulObject in a click callback in another file. For convenience, I have that callback wrapped in a method someLogic.

const PageComponent: React.FC = () => {
  return <Button onClick={(e) => someLogic(e)} />;
}

function someLogic(e: Event) { 
  const usefulObject = useUsefulObject();
  usefulObject.foo(e, ...); 
}

However, VS Code alerts that calling useUsefulObject in someLogic is a violation of the rules of hooks since it's called outside of a component method.

I can pass the object down (the below code works!) but it feels like it defeats the point of Contexts to avoid all the passing down. Is there a better way than this?

const PageComponent: React.FC = () => {
  const usefulObject = useUsefulObject();
  return <Button onClick={(e) => someLogic(e, usefulObject)} />;
}

function someLogic(e: Event, usefulObject) { 
  usefulObject.foo(e, ...); 
}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The hooks need to be called while the component is rendering, so your last idea is one of the possible ways to do so. Another option is you can create a custom hook which accesses the context and creates the someLogic function:

const PageComponent: React.FC = () => {
  const someLogic = useSomeLogic();
  return <Button onClick={(e) => someLogic(e)} />
}

function useSomeLogic() {
  const usefulObject = useUsefulObject();
  const someLogic = useCallback((e: Event) => {
    usefulObject.foo(e, ...);
  }, [usefulObject]);
  return someLogic;
}
about 4 years ago · Santiago Trujillo 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