• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

92
Vistas
useEffect dependancy array

I'm using customHook to fetch data from an API.

const useFetch = () => {
   const dispatch = useDispatch();
   return async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   };
};

and using it inside useEffect

const customFetch = useFetch();
useEffect(() => {
      (async () => {
         const data = await customFetch(fetchUsers, token);
         if (data) setUsers(data.user);
      })();
   }, [token]);

But eslint is complaining about the missing customFetch dependency. If I add it it will end up in an infinite loop. How can I fix this?

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So you just need useCallback here to make callback you return stable:

const useFetch = () => {
   const dispatch = useDispatch();
   const fetcher = useCallback(async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   }, [dispatch]);
   return fetcher;
};

useMemo and useCallback are specifically useful in cases like that, when you need something to be referentially the same, while creating/returning literally would provide new instance on each run(function, array, object)

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda