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

233
Views
this.state returning different values in console.log and display

I have a project that uses a class component to count the number of button presses. I got it to work, but when I console.log the count value, it returns a number one lower than the number displayed, even though they are using the same reference. I expected them to be the same number.

class ButtonCounter extends React.Component {
            constructor() {
                super()
                this.state = {
                    count: 0
                }
            }
            counter = 0
            getCount = () => {
                console.log('giving count')
                return this.counter
            }
            setCount = (amnt) => {
                this.counter += amnt
                this.setState({
                    count: this.counter
                })
                console.log(this.state.count) // returns -1 than the displayed value
            }
            render(){
                return(
                    <div>
                        <button onClick = {() => this.setCount(1)}>{this.state.count}</button>
                    </div>
                )
            }
        }

image of the code in browser

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

0

As stated in react docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

Source: https://reactjs.org/docs/react-component.html#setstate

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!