React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
What is the lifecycle methods order in mounting?
junior LevelCode ExampleHooksLifecycle
The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM.
scss
1. `constructor()`
2. `static getDerivedStateFromProps()`
3. `render()`
4. `componentDidMount()`
Code Example
tsx
import React, { Component } from 'react';
class MountingOrderTracker extends Component {
// Step 1: constructor initializes state and binds handlers
constructor(props: {}) {
super(props);
this.state = { initialized: true };
console.log('1. constructor()');
}
// Step 2: static getDerivedStateFromProps syncs state with props
static getDerivedStateFromProps(props: {}, state: { initialized: boolean }) {
console.log('2. static getDerivedStateFromProps()');
return null;
}
// Step 4: componentDidMount triggers after DOM is painted
componentDidMount() {
console.log('4. componentDidMount() - safe for DOM lookups & API calls');
}
// Step 3: render returns JSX
render() {
console.log('3. render()');
return <div>Mounting Phase Complete</div>;
}
}