U
U
uzi_no_uzi2020-05-04 14:27:46
JavaScript
uzi_no_uzi, 2020-05-04 14:27:46

Why is the hook called 2 times?

function MainPage() {


    let slider = React.createRef();
    let slideSpeed = 500;

    let [slidesCount, setSlidesCount] = useState(0);
    let [leftDragger, setLeftDragger] = useState(0);
    let [activeSlide, setActiveSlide] = useState(0);

   //Хук вызывается 2 раза
    useEffect(() => {
        setSlidesCount(document.querySelectorAll('.slick-list .slick-slide:not(.slick-cloned)').length)
        console.log(slidesCount) //Сначала выводит 0, потом 4
        
    }, [slidesCount]);
    


    let settings = {
        dots: false,
        infinite: true,
        speed: slideSpeed,
        slidesToShow: 1,
        slidesToScroll: 1,
        arrows: false,
        beforeChange: (currentSlide, nextSlide) => {
            setActiveSlide(nextSlide);
            console.log(leftDragger);

            if(activeSlide == 0) {
                setLeftDragger(100 / slidesCount * (activeSlide + 1) / 2 + "%");
            } else {
                setLeftDragger(20)
            }

    
        }
      };

    return(
        <div className="main-page">
            <section className="about">
               <Slider ref={slider} {...settings}>
               </Slider>
               <SliderNav slideSpeed={slideSpeed} sliderDOM={slider} />
            </section>
            <section className="remembers">
                
            </section>
        </div>
    )
    
}

export default MainPage;


There is such a code, useEffect is called 2 times, first it displays 0 elements (although there are 4 of them), and the second time already 4, why is this happening and how to fix it?

5eaffc0447b00468447595.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2020-05-04
@RomReed

because you initialize it with 0 then you subscribe to slidesCount and the hook is called with 0
let [slidesCount, setSlidesCount] = useState(0);

useEffect(() => {
        setSlidesCount(document.querySelectorAll('.slick-list .slick-slide:not(.slick-cloned)').length)
        console.log(slidesCount) //Сначала выводит 0, потом 4
        
    }, [slidesCount]);

and then you change the value of setSlidesCount(document.querySelectorAll('.slick-list .slick-slide:not(.slick-cloned)').length) and this hook is called again from 4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question