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

200
Vistas
useEffect fetch request is pulling data twice

What I Want:

I'm pulling data from an api, then setting the data to state. I've done this inside a useEffect hook, but when I console.log the data afterwards, it's displaying the data twice, sometimes 4 times. I'm at a loss as to why this is happening.

What I've Tried:

  • console.log within useEffect to see data from source
  • disabling react developer tools within chrome.

My Code:

// make api call, assign response to data state
const [apiData, setApiData] = useState();

useEffect(() => {
    async function fetchData() {
      try {
        await fetch('https://restcountries.com/v3.1/all')
        .then(response => response.json())
        .then(data => setApiData(data));
      } catch (e) {
        console.error('Error fetching api data', e);
      };
    };
    fetchData();
}, []);

console.log(apiData);

Result of console.log:

error screenshot

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

0

If you are using React version 18+, StrictMode has a behavior change. Before it wasn't running effects twice, now it does to check for bugs. ( Actually, it does mount-remount, which causes initial render effects to fire twice)

https://reactjs.org/blog/2022/03/29/react-v18.html#new-strict-mode-behaviors

about 4 years ago · Juan Pablo Isaza Denunciar

0

As was mentioned in the other comment this is due to effects being "double invoked" in strict-mode.

A common solution and one I believe has been suggested by the React team (although am struggling to find where I read this) is to use useRef.

// make api call, assign response to data state
const [apiData, setApiData] = useState();
const hasFetchedData = useRef(false);

useEffect(() => {
    async function fetchData() {
      try {
        await fetch('https://restcountries.com/v3.1/all')
        .then(response => response.json())
        .then(data => setApiData(data));
      } catch (e) {
        console.error('Error fetching api data', e);
      };
    };
    if (hasFetchedData.current === false) {
      fetchData();
      hasFetchedData.current = true;
    } 
}, []);
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