Gautam
Gautam

Reputation: 825

Where is the best palce to keep setInterval() in React component

I have created a React Carousel in which I am calling setInterval method in componentDidMount method as below but seems like React is throwing me warning as attached below. Am i doing it wrong? ideally componentDidMount should be called only once and my code should work fine.

componentDidMount() {
    const self = this;

    if(self.props.autoPlay) {
      setInterval(() => {
        if(self.state.current != self.props.images.length - 1){
          self.handleTransition(self.state.current + 1);
        } else {
          self.handleTransition(0);
        }
      }, 3000);
    }
  }

enter image description here

Upvotes: 1

Views: 220

Answers (2)

croraf
croraf

Reputation: 4720

I was also using a variable inside a module where the component is defined. Something like:

//Clock.js

let timerID;

class Clock extends React.Component {

  componentDidMount() {
    timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(timerID);
  }

  tick() {
    console.log('tick');
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
      </div>
    );
  }
}

Maybe someone can comment why is this.timerID (as mentioned in Using setInterval in React Component) preferred?

Upvotes: 1

Fabian Schultz
Fabian Schultz

Reputation: 18546

Set the interval as a property of the component, then clear the interval once the component unmounts:

componentDidMount() {
  const self = this;

  if(self.props.autoPlay) {
    self.interval = setInterval(() => {
      if(self.state.current != self.props.images.length - 1){
        self.handleTransition(self.state.current + 1);
      } else {
        self.handleTransition(0);
      }
    }, 3000);
  }
}

componentWillUnmount() {
  clearInterval(this.interval);
}

Upvotes: 1

Related Questions