Autoplay CarouselLoading saved progress…

Autoplay Carousel

Build an image carousel as a single React component. Four colored slides sit stacked in a viewport; the carousel advances itself on a timer, pauses while the pointer is over it, and offers manual controls. The whole trick is one timer and one index — and making sure that timer is created and cleared at exactly the right moments so intervals never pile up.

Task

The starter App.tsx renders the carousel in its resting state — slide 1 showing, arrows, and four dots with the first one active — but nothing moves. Make it work:

  1. Track the slide. Hold the active index with useState(0).
  2. Autoplay. In a useEffect, setInterval every 3000ms to advance setIndex((i) => (i + 1) % 4). Return a cleanup that clearIntervals it.
  3. Pause on hover. The viewport's onMouseEnter pauses autoplay; onMouseLeave resumes it.
  4. Manual controls. Prev/Next arrows step the index (wrapping both ways); clicking a dot jumps to that slide, and the active dot reflects index.

Examples

  • On load, slide 1 is visible and dot 1 is filled. Three seconds later it advances to slide 2, then 3, then 4, then wraps back to 1.
  • Moving the pointer onto the carousel freezes it on the current slide; moving it off resumes the 3-second cycle.
  • Clicking Next jumps ahead immediately; clicking the third dot jumps straight to slide 3.

Notes

  • One timer, cleared every time. The useEffect cleanup must clearInterval — otherwise each re-run stacks another interval and the carousel races.
  • Functional updates. setIndex((i) => (i + 1) % 4) reads the latest index, so the effect doesn't need index in its deps (which would re-create the timer every tick).
  • Wrapping. Use (i + step + 4) % 4 for the arrows so Prev from slide 1 lands on slide 4.
  • Styling (viewport, slides, arrows, dots) is already in styles.css; focus on the state and the timer.
Loading editor…
Loading preview…