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

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

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 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