state is a way to store and update data or information that a component has.
As mentioned in a previous post, a component must be defined as a class component in order to use state
#1. Adding Local State to a Class
Use a class constructor in order to assign initial this.state to a component.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}Class components should always call the base constructor with props. by passing props to the base constructor, it — but why?
#2. Adding Lifecycle Methods to a Class
Using the example of the Clock component writeen in section 1,
mounting: set up a timer whenever the Clock is rendered to the DOM for the first time
unmounting: clear the timer whenever the DOM produced by the Clock is removed
this is the order of how React inserts components into the DOM:
Like below, you can do mounting and unmounting by using componentDidMount() and componentWillUnmount() respectively.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}compononetWillMount()render() methodcompononetDidMount()render() methodcomponentWillMount())this.setState(), which will trigger a re-render, therefore, displayed on the browserfetch data from a servercomponentWillUnmount()event listeners added in componentDidMount()componentDidMount()