useCarousel
A custom hook to handle carousel/slider logic with autoplay, loop, and manual navigation.
✅ Features
- Seamless next/previous navigation
- Looping support
- Auto-play with customizable interval
- Manual navigation with goTo(index)
📦 Usage
1import { useCarousel } from './useCarousel'; 2 3const { current, next, prev, goTo } = useCarousel({ 4 total: 5, 5 loop: true, 6 autoPlay: true, 7 interval: 3000, 8}); 9 10return ( 11 <div> 12 <button onClick={prev}>Previous</button> 13 <div>Current Slide: {current}</div> 14 <button onClick={next}>Next</button> 15 </div> 16);
📋 Source Code
This is the full implementation of useCarousel
1import { useState, useEffect, useRef } from 'react';
2
3interface CarouselOptions {
4 total: number;
5 loop?: boolean;
6 autoPlay?: boolean;
7 interval?: number;
8}
9
10export function useCarousel({ total, loop = true, autoPlay = false, interval = 3000 }: CarouselOptions) {
11 const [current, setCurrent] = useState<number>(0);
12 const timerRef = useRef<NodeJS.Timeout | null>(null);
13
14 const next = () => setCurrent(prev => loop ? (prev + 1) % total : Math.min(prev + 1, total - 1));
15 const prev = () => setCurrent(prev => loop ? (prev - 1 + total) % total : Math.max(prev - 1, 0));
16 const goTo = (index: number) => setCurrent(index);
17
18 useEffect(() => {
19 if (autoPlay) {
20 timerRef.current = setInterval(next, interval);
21 return () => {
22 if (timerRef.current) {
23 clearInterval(timerRef.current);
24 timerRef.current = null;
25 }
26 };
27 }
28 return undefined
29 }, [autoPlay, interval, total]);
30
31 return { current, next, prev, goTo };
32}
33