Dorokhov.codes
06. Component states
To create a state object we need to set a state
property. We can change this property anytime unlike the props
one.
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 1234
};
}
render() {
return <h2>{this.state.number}</h2>;
}
};
How to change states?
We shouldn’t change the state
object directly. We should use the setState()
method instead.
When we don’t depend on the previous state (text typing, for example):
this.setState({
number: 1235
});
When the previous state is important we use callback function, so it will be called after all previous states are updated.
this.setState(state => ({
number: 1235
}));
We don’t need to pass to the setState()
an object with all the properties. It can be even one property. This property will be overwritten and the rest will
be left the same.
What will happen?
Usually after calling the setState()
method the render()
method will be triggered.
Controlled and uncontrolled inputs
https://goshacmd.com/controlled-vs-uncontrolled-inputs-react/