Intro to
State
Objectives
-
Define state in React
-
Create a component with a constructor and state
-
Describe what happens when setState is called
State
Stateful data
Data in our application that can change
State Example
class App extends Component {
constructor(props) {
super(props);
this.state = { favColor: 'red' };
}
render() {
return (
<div>
My favorite color:
{this.state.favColor}
</div>
);
}
}
setState
The correct way to change state in your application
this.setState({ });
Simplest Usage: setState accepts an object with new properties and values for this.state
class App extends Component {
constructor(props) {
super(props);
this.state = { favColor: 'red' };
setTimeout(() => {
this.setState({favColor: 'blue'})
}, 3000);
}
render() {
return (
<div>
My favorite color:
{this.state.favColor}
</div>
);
}
}
Intro To State
By Elie Schoppik
Intro To State
- 2,090