state is the plain JavaScript object which is used in the React Component , which contain information related the Component state. state control the behavior of the component
setState() function used to change the state information.
as you can see the following component have state type which display in the component html render.
if we change the state type information than it reflect in the html change
class Type extends React.Component {
constructor() {
super();
this.state = {type: 'timer'}
}
render() {
return (
<div>
{this.state.type}
</div>
);
}
}
initial state.type is is timer so it will display timer there in render element.
if we add setState , lets see how setState work by example in react
class Type extends React.Component {
constructor() {
super();
this.state = {type: 'timer'}
this.changeState = this.changeState.bind(this);
}
changeState(){
this.setState({type:'stopwatch'})
}
render() {
return (
<div>
{this.state.type} <button onClick={this.changeState} >Click to change Type</button>
</div>
);
}
}
here on click event we calling changeState function will invoke setState function to change the state.type to stopwatch and it reflect it in the html.
we need to bind the function in constructor like this :
this.changeState = this.changeState.bind(this);
and in the changeState function call setState :
this.setState({type:'stopwatch'})