React limits the number of renders to prevent an infinite loop - react hooks

394 Views Asked by At

I have a simple section in which contains a slick slider I want on clicking a button eg button 1 it should open a specific slide.

Here is the live demo on codesandbox slick go to slide

Here is the js code

import React, { useRef, useState, useEffect } from "react";
import Slider from "react-slick";

export default function APP() {
  const sliderRef = useRef();
  const [slideIndex, setSlideIndex] = useState(0);

  var settings = {
    dots: true
  };

  useEffect(() => {
    sliderRef.current.slickGoTo(slideIndex);
  }, [slideIndex]);

  return (
    <div className="container">
      <Slider {...settings} ref={sliderRef}>
        <div>
          <img src="http://placekitten.com/g/400/200" />
          <button onClick={setSlideIndex(0)}>btn 1</button>
          <button onClick={setSlideIndex(1)}>btn 2</button>
          <button onClick={setSlideIndex(2)}>btn 3</button>
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
        <div>
          <img src="http://placekitten.com/g/400/200" />
        </div>
      </Slider>
    </div>
  );
}

but I get the following error

Too many re-renders. React limits the number of renders to prevent an infinite loop

What is wrong here?

1

There are 1 best solutions below

1
On BEST ANSWER

Your onClick props should be functions, not function calls.

So this

onClick={setSlideIndex(0)}

Should be this:

onClick={() => setSlideIndex(0)}

The way you have it now, the function is called when the component renders. And the function changes the state, which causes a re-render, which calls that function again, which triggers a state change, etc. etc. -> infinite loop