Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Correct way to clear interval in component did mount in React

Im trying to clear an interval when the component is unmounted in a class based component in react. I have done some research on this and saw that in the componentWillUnmount lifecycle function, people are storing the actual function in a variable instead of just straight away clearing the interval. For example:

      componentDidMount() {
        const { stock } = this.props;
// Fetch data once user lands on page
        this.fetchData(stock);
// Fetch data every hour
        setInterval(() => {
          this.fetchData(stock);
          console.log('setInterval ran');
        }, 3600000);
      }
   
    
      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
        const refreshFetch = clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }
    
      async fetchData(stock) {
        const data = await getAvgPriceHistory(stock);
        if (data && data[stock].length) {
          const dataArray = data[stock].map((arr) => {
            return arr[1];
          }).reverse();
          this.setState({
            data: dataArray,
            isLoaded: true
          });
        } else {
          // straight line if not found.
          this.setState({
            data: [1, 1],
            isLoaded: true
          });
        }
        console.log('Data fetched!');
      }

Meanwhile, the way I am used to doing this in the componentWillUnmount function without defining a variable like so:

      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
       clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }

Is there any benefits to doing one or the other?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

setInterval return an id. You can use it with clearInterval to destroy it.

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

let intervalId;

...

intervalId = setInterval(fn, time);

...

clearInterval(intervalId);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!