import React from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
constructor(props)
{
super(props);
this.state = { hello : "World!" };
}
componentWillMount()
{
console.log("componentWillMount()");
}
componentDidMount()
{
console.log("componentDidMount()");
}
changeState()
{
this.setState({ hello : "Geek!" });
}
render()
{
return (
<div>
<h1>GeeksForGeeks.org, Hello{ this.state.hello }</h1>
<h2>
<a onClick={this.changeState.bind(this)}>Press Here!</a>
</h2>
</div>);
}
shouldComponentUpdate(nextProps, nextState)
{
console.log("shouldComponentUpdate()");
return true;
}
componentWillUpdate()
{
console.log("componentWillUpdate()");
}
componentDidUpdate()
{
console.log("componentDidUpdate()");
}
}
ReactDOM.render(
<Test />,
document.getElementById('root'));
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
What is the order that Class components run when React initialize and mounts
the components.
1. Regardless of React Components, constructors are always ran first
1. In constructor, you will just initialize the state in constructor
2. Render runs second, which determines what to show. This is the template
of the HTML and dictates the UI is going to be.
3. Third one that runs is componentDidMount, React runs the constructor,
runs the render and mounts the initial state and mounts on. Then it
will runs the code in componentDidMount();
- When setState() is called, the render() method will be called again and
re-renders.
- Every subsequent child with a different props will also be re-rendered.