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

127
Vistas
Reuse my custom hook `useFetch` in React?

I've created a simple useFetch custom hook which allows me to call any Url I want :

import React, { useState, useEffect } from 'react';


export default function useFetch(url) {
  console.log(url)
  const [data, setData] = useState([]);
 
  useEffect(() => {
    fetch(url)
      .then((response) => {
        if (response.ok) return response.json();
        setData([]);
      })
      .then((data) => {
       
        setData(data)})
      .catch((err) => {
        console.error(err);
        setData([]);
      });
  }, [url]);

 
  return { data} ;
}

In my Main component I'm loading a static list of items.( via useEffect with [] becuase it's static)

I currently do it via :

export function Courses() {
   
  const [langs, setLangs] = useState([]);

  useEffect(() => {
    getData(config.url).then((f) => setLangs(f));
  }, []);
...

Where getData is:

export function getData(uri) {
  return fetch(uri).then(response =>
    response.json()
  );
}

The problem is that I can't (don't know how) I can use my useFetch here becuase it can't be inside useEffect , and that's why I've created the additional getData method.

ps -

In other "details" component I use useFetch perfectly fine :

export default function Details({ langId }) {
  const { data: teachers } = useFetch(`${config.url}/${langId}`);
  ...

The problem is only in the main component where I don't want to fetch manually . I want to use my useFetch. How can I do that ?

I want that Courses will load the static list only once via useFetch

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

One possible option is to cache the fetch response (I didn't test the code)

import React, { useState, useEffect } from 'react';

const cache = {};

export default function useFetch(url, useCache=false) {
  console.log(url)
  const [data, setData] = useState([]);
 
  useEffect(() => {
    if (useCache && cache[url]) {
      setData(cache[url]);
    } else {

    fetch(url)
      .then((response) => {
        if (response.ok) {
          const responseData = await response.json();
          if (useCache) cache[url] = responseData;
          return responseData;
        }
        setData([]);
      })
      .then((data) => {
       
        setData(data)})
      .catch((err) => {
        console.error(err);
        setData([]);
      });
    }
  }, [url]);

 
  return { data} ;
}

You can use useRef if you want to keep the hooks as a pure function

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