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

198
Views
The counter in react executed twice in both given component

I am tring to make a simple counter and display it to the page. But it renders unexpected o/p. The counter counts a value twice in example 1 but works perfect as i want in example 2. What is the reason for not working in ex.1. What is the background process for this.

// Example: 1
import React, { Component } from 'react';
class Counter extends Component {
    constructor() {
        super()
        this.state = {
            count: 0,
            isFirstTime: true
        }
    }
    in() {
        console.log('How many time function called?'); // consoled one time
        if (this.state.isFirstTime) {
            this.setState({
                isFirstTime: false
            })
            setInterval(() => {
                this.setState({
                    count: this.state.count + 1
                })
            }, 1000)
        }
    }
    render() {
        return (
            <div>
                {this.state.isFirstTime && this.in.apply(this)}
                Counter: {this.state.count}
            </div>
        )
    }
}

export default Counter;

// Example: 2
import React, { Component } from 'react';

let isFirstTime = true;

class Counter extends Component {
    constructor() {
        super()
        this.state = {
            count: 0
        }
    }
    in() {
        console.log('How many time function called?'); // consoled one time
        if (isFirstTime) {
            isFirstTime = false
            setInterval(() => {
                this.setState({
                    count: this.state.count + 1
                })
            }, 1000)
        }
    }
    render() {
        return (
            <div>
                {isFirstTime && this.in.apply(this)}
                Counter: {this.state.count}
            </div>
        )
    }
}

export default Counter;

I am running it on React.StrictMode.

about 4 years ago · Juan Pablo Isaza
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!