# State
React components has a built-in state object. The state object is where you store properties that bleongs to the component. When this object changes, the component re-renders.
# How can we use the State object?
Refer to the state object in the render() method like the example below:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: 'Ford',
model: 'Mustang',
color: 'red',
year: 1964,
};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}
# Updating the State object
To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value.
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: 'Ford',
};
}
changeBrand = () => {
this.setState({ color: 'Audi' });
};
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<button type="button" onClick={this.changeBrand}>
Change brand
</button>
</div>
);
}
}
WARNING
Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).
# What is the difference between state and props?
props and state are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: props get passed to the component (similar to function parameters) whereas state is managed within the component (similar to variables declared within a function).