Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!