I would like to ask why my state is not changing when I do an onclick event. I\'ve search a while ago that I need to bind the onclick function in constructor but still the s
According to React Docs
React does not guarantee that the state changes are applied immediately. This makes reading this.state right after calling setState() a potential
pitfall
and can potentially return theexisting
value due toasync
nature . Instead, usecomponentDidUpdate
or asetState
callback that is executed right after setState operation is successful.Generally we recommend usingcomponentDidUpdate()
for such logic instead.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
counter: 1
};
}
componentDidUpdate() {
console.log("componentDidUpdate fired");
console.log("STATE", this.state);
}
updateState = () => {
this.setState(
(state, props) => {
return { counter: state.counter + 1 };
});
};
render() {
return (
Hello CodeSandbox
Start editing to see some magic happen!
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render( , rootElement);