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

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

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