Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting.
Mounting
Mounting means putting elements into the DOM.
React has four built-in methods that gets called, in this order, when mounting a component:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render()
method is required and will always be called, the others are optional and will be called if you define them.
Constructor
The constructor()
method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state
and other initial values.
The constructor()
method is called with the props
, as arguments, and you should always start by calling the super(props)
before anything else, this will initiate the parent’s constructor method and allows the component to inherit methods from its parent (React.Component
).
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: "Folau"}; } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
The getDerivedStateFromProps()
method is called right before rendering the element(s) in the DOM. This is the natural place to set the state
object based on the initial props
. It takes state
as an argument, and returns an object with changes to the state
.
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: ""}; } static getDerivedStateFromProps(props, state) { return {name: props.name }; } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile name="Folau"/>, document.getElementById('root'));
render()
The render()
method is required, and is the method that actually outputs the HTML to the DOM.
The componentDidMount()
method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.
class Profile extends React.Component { constructor(props) { super(props); this.state = {name: "Folau"}; } componentDidMount() { setTimeout(() => { this.setState({name: "Lisa"}) }, 1000) } render() { return ( <h1>My name is {this.state.name}</h1> ); } } ReactDOM.render(<Profile />, document.getElementById('root'));
Updating
The next phase in the lifecycle is when a component is updated.
A component is updated whenever there is a change in the component’s state
or props
.
React has five built-in methods that gets called, in this order, when a component is updated:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The render()
method is required and will always be called, the others are optional and will be called if you define them.