useCarousel

The useCarousel hook is used inside the Carousel component. This hook handles the slider logic, inside the Carousel component.

Code

import { useState } from "react"

export default function useCarousel(initialValue, imageListLength){
    const [currentSlide, setCurrentSlide] = useState(initialValue);

    function handleLeftArrow() {
        currentSlide === 0 ? setCurrentSlide(imageListLength - 1) : setCurrentSlide(currentSlide - 1);
    }
    
    function handleRightArrow() {
        currentSlide === imageListLength - 1 ? setCurrentSlide(0) : setCurrentSlide(currentSlide + 1);
    }

    return [currentSlide, handleLeftArrow, handleRightArrow];
}

Explanation

  • As you can see above it uses the useState hook of the React internally for managing the state of slider on arrow click.

  • It accepts two parameters - a initialValue, which is an integer (default value is zero) and imagesListLength - the array length containing source links for each image.

  • It returns the following:

    • currentSlide - index of the current slide.

    • handleLeftArrow - function to manage previous button click.

    • handleRightArrow - function to manage right button click.

Last updated