-1

Please see the below code. When I click the right icon it gives me twice the value of current property of useState hooks. Now I can't fix that. Can you please tell me how to fix this?

import React, { useState } from "react";
import { SliderData } from "./SliderData";
import { FaArrowAltCircleRight, FaArrowAltCircleLeft } from "react-icons/fa";
const ImageSlider = (slides) => {
  const [current, setCurrent] = useState(0);
  const length = slides.length;
  console.log(current);

  const nextSlide = () => {
    setCurrent(current === length - 1 ? 0 : current + 1);
  };
  const prevSlide = () => {
    setCurrent(current === 0 ? length - 1 : current - 1);
  };
  //   if (!Array.isArray(slides) || length <= 0) {
  //     return null;
  //   }
  return (
    <section className="slider">
      <FaArrowAltCircleLeft className="left-arrow" onClick={prevSlide} />
      <FaArrowAltCircleRight className="right-arrow" onClick={nextSlide} />
      {SliderData.map((slide, index) => {
        return (
          <div
            className={index === current ? "slide active" : "slide"}
            key={index}
          >
            {index === current && (
              <img src={slide.image} alt="this is image" className="image" />
            )}
          </div>
        );
      })}
    </section>
  );
};

export default ImageSlider;
  • Are you using ``? [That will render components twice in development](https://stackoverflow.com/a/61897567/1377002). – Andy May 21 '22 at 11:32
  • Also, you should be using `setCurrent(current => current === length - 1 ? 0 : current + 1); ` instead of `setCurrent(current === length - 1 ? 0 : current + 1);`. Same for the one below this – Tanay May 21 '22 at 11:34
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community May 21 '22 at 12:38
  • Is your objective here optimizing performance? So you have 1 render instead of 2, right? – Igor Loskutov May 21 '22 at 13:06

0 Answers0