State & life cycle
state
State is similar to props, but state is private and fully controlled by the current component.
Convert function components to class components
Use the following five steps to convert function components into class components:
1. Create an ES6 class with the same name and inherit from React.Component.
2. Add an empty render() method.
3. Move the function body to the render() method.
4. Use this.props to replace props in the render() method.
5. Delete the remaining empty function declarations.
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {
this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
Add local state to the class component
We move date from props to state in the following three steps:
1. Replace this.props.date in the render() method with this.state.date
2. Add a class constructor, and then this in the function. Assign initial value to state
3. Remove the date attribute in the Clock element:
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>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Add life cycle methods to Class
The componentDidMount() method will run the
componentWillUnmount() lifecycle method to clear the timer after the component has been rendered into the DOM
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>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Use State correctly
There are three things you should know about setState():
Do not directly modify State using setState():
this.setState({
comment: 'Hello'});
State update may be asynchronous
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));