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

268
Vistas
Why I have a loop in my react application?

I'm learning React and I'm making my application to test the library but I've got a strange loop and I don't figure out where does it come from.

My code :

import React, {useEffect, useState} from 'react';
import Navigation from "../components/Navigation";
import axios from "axios";
import Card from "../components/Card";
import {randomNumber} from "../components/_helper";

const Home = () => { 
    console.log('coucou')

    const [randomCharacters, setRandomCharacters] = useState([]);
    const [totalCharacters, setTotalCharacters] = useState('');
    const [randomNumbers, setRandomNumbers] = useState('');


    useEffect(() => {
        axios.get('https://rickandmortyapi.com/api/character')
            .then((response) => {
                setTotalCharacters(response.data.info.count)
            })
    })

    useEffect(() =>{
        axios.get('https://rickandmortyapi.com/api/character/1,23,45,654,21,12')
            .then((response) => {
                response.data.map(() => (
                    setRandomCharacters(response.data)
                ))
            })
    })
    return (
        <div>
            <Navigation/>
            {randomCharacters.map( (character) => (
                <Card key={character.id} character={character}/>
            ))}
        </div>
    );
};

export default Home;

As you can see, I did a console.log at the beginning of my code and I have no loop writing (for, foreach) but this is what happen in the console :

result from the console

I don't understand this behavior, someone to explain where I did wrong ?

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

0

Your 2 useEffects run every time when re-render occurs.

In your useEffect, you update state variables randomCharacters and totalCharacters. Then re-render occurs whenever your APIs return different data because of these state updates.

So your app loops infinitely.

At least you need to add one more dependency. But in your case, you can pass empty dependency [] for one time API call.

Here is a tip from React official document. If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

Code should look like the following:

    useEffect(() => {
        axios.get('https://rickandmortyapi.com/api/character')
            .then((response) => {
                setTotalCharacters(response.data.info.count)
            })
    }, [])

useEffect(() =>{
        
    axios.get('https://rickandmortyapi.com/api/character/1,23,45,654,21,12')
            .then((response) => {
                response.data.map(() => (
                    setRandomCharacters(response.data)
                ))
            })
    }, [])
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