noBoom
noBoom

Reputation: 145

Why useRef is coming undefined when component first mounts?

Why useRef is coming undefined first? on second click i get the current object. I don't want to click twice to stop carousel.

I want current to be available when App component first mounts. What i am doing wrong here?

import {useState, useRef} from "react";
import Slider from "react-slick";

function App(){

   const [autoPlay, setAutoPlay] = useState(false);
   const carousel = useRef();

   const settings = {
      infinite: true,
      autoplay: true,
      speed: 1000,
      autoplaySpeed: 1000,
      pauseOnHover: false,
   };
   
   function handlePlay(){
      setAutoPlay(!autoPlay);
      autoPlay ? carousel.current.slickPause() : carousel.current.slickPlay();
   }

   return (
     <div>
       <Slider ref={carousel} {...settings}>
            <div>1</div>
            <div>2</div>
            <div>3</div>
       </Slider>
       <button type='button' onClick={() => handlePlay()}>Click</button>
     </div>
   );
}

Upvotes: 1

Views: 461

Answers (1)

user18821127
user18821127

Reputation: 366

Just check if ref.current exists. The why is because of how React assigns ref to the node after calculating the DOM (don't quote me on this- I can't find the docs to reference and don't exactly remember the exact wording)

Upvotes: 2

Related Questions