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

261
Views
Why React Class Component and Function Component output is different in setTimeout?

A class component and a function component, both of which can click on the div to modify the value of num.

export default function App() {
  const [num, setNum] = useState(0);
  const click = () => {
    setTimeout(() => {
      console.log(num, "3000");
    }, 3000);
    setNum(num + 1);
  };

  return <div onClick={click}>click {num}</div>;
}
export default class App extends React.Component {
  state = {
    num: 0
  };

  click = () => {
    setTimeout(() => {
      console.log(this.state.num);
    }, 3000);
    this.setState({ num: this.state.num + 1 });
  };

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

Why is the output of num different in the above two components after clicking

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

0

In class components, when state is set, when the component updates, the new state will be assigned to the state property of the instance. To oversimplify, doing

this.setState(someNewState);

eventually results in React doing something like

theInstance.state = mergedNewState;

As a result, referencing this.state will result in changes being seen if the state updates, because this.state points to something new..


Functional components are different. Unlike class components, nothing gets (visibly) mutated when using their state. Instead, when you call a state setter, the whole function (component) runs again, and the calls to useState return a new value.

In your code, the

const [num, setNum] = useState(0);

results in a num that the click function closes over.. If there's a click, when the timeout callback runs, it'll still close over the same num that was created before the click handler runs. The component will re-render with a new click function, which has a new num number that it closes over, but the old click function will still be referencing the num from the render in which that old function was created.

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!