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

155
Vistas
function called from useEffect rendering too fast and breaks, works correctly after re-render

I am using React-id-swiper to load images for products. Let's say I have 5 products.

I am trying to use a function to detect when every image is successfully loaded, then when they are, set the useState 'loading' to false, which will then display the images.

I am using a variable 'counter' to count how many images there are to load. Once 'counter' is more than or equal to the amount in the list (5), set 'loading' to FALSE and load the images.

However, I am noticing that when I console log 'counter' when running it from useEffect, it ends at '0' and renders 5 times. 'Loading' also remains true.

However, if I trigger a re-render, I see 1,2,3,4,5 in the console. 'Loading' then turns to false.

I suspect this is to do with useEffect being too fast, but I can't seem to figure it out. Can somebody help?

Code:


  const { products } = useContext(WPContext);
  const [productsList, setProductsList] = useState(products);
  const [filteredList, setFilteredList] = useState(products);
  const [loading, setLoading] = useState(false);


useEffect(() => {
    loadImages(products);
  }, []);

  const loadImages = (allProducts) => {
    let counter = 0;
    setLoading(true);
    const newProducts = allProducts.map((product) => {
      const newImg = new Image();
      newImg.src = "https://via.placeholder.com/450x630";
      newImg.onload = function () {
        counter += 1;
      };

      // At this point, if I console log 'counter', it returns as 0. If I trigger a re-render, it returns as 1,2,3,4,5

      return {
        ...product,
        acf: {
          ...product.acf,
          product_image: {
            ...product.acf.product_image,
            url: newImg.src,
          },
        },
      };
    });
    handleLoading(newProducts, counter);
  };

  const handleLoading = (newProducts, counter) => {
    if (counter >= filteredList.length) {
      setLoading(false);
      counter = 0;
      setFilteredList(newProducts);
    }
  };
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

First weird thing is that you are calling the handleLoading() function before its even defined. This is probably not a problem but a weird practice.

You are also creating a new variable counter when you pass it in as an argument. You aren't actually reseting the counter that you want.

Also using onload is unnecessary and can cause weird behavior here since its not a synchronous operation but event based. As long as you set the img.src it should force it to load.

Try this:

const loadImages = (allProducts) => {
    let counter = 0;
    setLoading(true);
    const newProducts = allProducts.map((product) => {
      const newImg = new Image();
      newImg.src = "https://via.placeholder.com/450x630";
      counter += 1;

      return { ...product, acf: { ...product.acf, product_image: { ...product.acf.product_image, url: newImg.src }}};
    });

    const handleLoading = (newProducts) => {
      if (counter >= filteredList.length) {
        setLoading(false);
        counter = 0;
        setFilteredList(newProducts);
      }
    };
    handleLoading(newProducts);
};

useEffect(() => {
    loadImages(products);
}, []);
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