Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda