DEV Community

Cover image for Project 21 of 100 - Only Fans React Carousel
James Hubert
James Hubert

Posted on

Project 21 of 100 - Only Fans React Carousel

Hey! I'm on a mission to make 100 React.js projects ending March 8th. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Link to today's deployed app: link
Link to the repo: github

After a multi-week break from creating daily projects in React I realized yesterday that there were some concepts that I knew but was rusty on, and a few simple practices creating yesterday's project that intimidated me.

I wanted to brush up on some simple skills today and create just the hero section of a simple e-commerce website. This website is dedicated to selling only fans- personal, office, commercial, you name it. The site is called Only Fans (not my original joke I assure you).

Creating a carousel in React from scratch was surprisingly hard. I've been getting used to writing most of my components to be functional rather than class-based, so I needed to use useState and useEffect to change a number in state later used to reference an image in an array of images.

I found out the hard way that setInterval in React is somewhat tricky because every time the setInterval method counts down, in my case it sets state and thus causes a re-render, which causes an infinite loop. So the solution for this was useEffect.

See my code below for this rather difficult but neat implementation:

function Hero() {
  const [heroImageIdx, setHeroImageIdx] = useState(0);

  const runCarousel = () => {
    const interval = setInterval(() => {
      setHeroImageIdx((prevIdx) => prevIdx + 1);
    }, 5000);
    return () => clearInterval(interval);
  };

  useEffect(() => {
    runCarousel();
  }, []);

  return (...)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
samuelcasey profile image
samuel-casey

this is hilarious 😂