0

I have this carousel component that I'm calling from a page but it's not showing until I refresh the page. If I have the Box component and switch to the Carousel component it doesn't work until I refresh the page but if I render the Carousel component first, render Box then go back to Carousel it works. Is this a bug with ReactDOM or what?

My carousel component:

const Carousel = () => {
  const { carousel, setCarousel } = useContext(AppContext);

  useEffect(() => {
    setCarousel(true);
    return () => {
      setCarousel(false);
    };
  }, [carousel]);

  const items = ["image1.svg", "image2.svg", "image1.svg", "image2.svg"];

  const responsive = {
    0: { items: 1 },
    1024: { items: 2 },
  };

  return (
    <div
      className={`container flex`}
      style={{
        marginTop: "40px",
      }}>
      <AliceCarousel
        disableDotsControls
        disableButtonsControls
        autoHeight={true}
        autoWidth={true}
        responsive={responsive}
        animationType='slide'>
        {items.map((i, index) => (
          <img src={i} key={index} alt='' srcSet='' className={Styles.slider} />
        ))}
      </AliceCarousel>
         </div>
  );
};

And I'm switching/calling it on another component like this:

const { carousel, modalIsOpen, openModal, closeModal } = useContext(
  AppContext
);

return (
  <div className={carousel ? Styles.layout : ""}>
    <div>
      <Box />
    </div>
  </div>
)

I need to make the component re-render when it's called or something so that it works properly, even when I call the AliceCarousel component on my page directly I still have this issue.

Is this something to do with React or the component itself? Thanks

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
tylerdurden
  • 101
  • 4

1 Answers1

1

Your useEffect logic leads to infinity loop as after changing the state to true, by having the state in dep array [carousel], you changing it back to false from the cleanup function.

// Useless useEffect, always false.
useEffect(() => {
    setCarousel(true);
    return () => {
      setCarousel(false);
    };
}, [carousel]);
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • That's not it, if I don't return setCarousel to false then the carousel will always stay true. I need to set it to false when the component is unmounted. I have to completely render the carousel when the page loads so that it works when I switch from the box component to it – tylerdurden Jan 07 '21 at 09:57