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

160
Views
Why the output is different between Class Component and Function Component

There are two different types of components, each modifying the value of num continuously when the button is clicked, why the output of the two components is different.

Class Component

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      num: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    setTimeout(() => {
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      console.log(this.state.num); // 0, 3, 6...
    }, 0);
  }

  render() {
    return <button onClick={this.handleClick}>{this.state.num}</button>;
  }
}

Function Component

export default function App() {
  const [num, setNum] = useState(0);

  const handleClick = () => {
    setTimeout(() => {
      setNum(num + 1);
      setNum(num + 1);
      setNum(num + 1);
      console.log(num); // 0, 1, 2, 3...
    }, 1000);
  };

  return <button onClick={handleClick}>{num}</button>;
}
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!