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

173
Views
Am I using React hooks wrong?

I wanted to create a sevice-like hook that doesn't hold state, it just exports an object with funtions.

I first started with this:

export default useFoo = () => ({ // some functions here... });

But then I realized that this wouldn't be the best approach because a new object is going to be created every time the hook is called and I don't want that - I need one global object with the same reference across all components, so then I tried this:

const foo = { // some functions here... };
export default useFoo = () => foo;

It works as expected, but I'm not sure if it's the right way to do it. Is there a better way to achieve this? Or should I use context maybe?

EDIT: I know that I can just export a plain JS object and not bother myself with hooks, but I need it to be a hook because I use other hooks inside.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It works as expected, but I'm not sure if it's the right way to do it. Is there a better way to achieve this?

If foo never changes, and doesn't need to close over any values from the other hooks you're calling in useFoo, then that's fine. If it does need to change based on other values, then you can use useCallback and/or useMemo to only recreate the object when relevant things change.

export default useFoo = () => {
  const something = useSomeHook();

  const foo = useMemo(() => {
    return { /* some functions that use `something` */ }
  }, [something]);

  return foo;
}
about 4 years ago · Juan Pablo Isaza 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!