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>;
}