Phase | Description |
---|---|
Mounting Phase | This phase occurs when an instance of a component is being created and inserted into the DOM. |
Updating Phase | This phase occurs when a component is being re-rendered as a result of changes to either its props or state. |
Unmounting Phase | This phase occurs when a component is being removed from the DOM. |
Component lifecycle methods are special methods that get called at various stages of a component's life.
Mounting Phase | Updating Phase | Unmounting Phase |
---|---|---|
constructor() | getDerivedStateFromProps | componentWillUnmount |
getDerivedStateFromProps | shouldComponentUpdate | |
render | render() | |
componentDidMount | getSnapshotBeforeUpdate | |
componentDidUpdate() |
-
A constructor is a special method that is called when an instance of a class is created.
-
Constructors are used for initializing the component's state or performing any setup needed before the component is rendered.
class ConstructorExample extends Component {
constructor(props) {
super(props);
// Initialize the state
this.state = {
count: 0,
};
}
render() {
return(
<h2>Count: {this.state.count}</h2>
);
}
}
export default ConstructorExample
- The
super
keyword is used in the constructor of a class component tocall the constructor of the parent class
. - This is necessary to ensure that the initialization logic of the parent class is executed.
Render() method returns the React elements
that will be rendered to the DOM.
-
Two step process to maintain state:
-
this.setState()
method is used to update the state. -
this.state
property is used to render the update state in DOM.
-
componentDidMount() lifecycle method in React is the part of mounting phase and is called after a component has been rendered
to the DOM.
- Mostly used for
side effects
. For example, external data fetching or setting up subscriptions.
// Fetch data from API example using
// componentDidMount life cycle method
class CompDidMount extends Component {
constructor(props) {
// 1. Component initialization
this.state = {
data: null
};
}
// 2. componentDidMount is called after the component is added to the DOM
componentDidMount() {
// 3. Fetch data from an API and update state with fetch data
fetchData().then((data) => {
this.setState({ data });
});
}
// 4. Render the component's UI using the fetched data.
render() {
return (
<div>
<p>Data: {this.state.data}</p>
</div>
);
}
}
export default CompDidMount;