Q3.React LifeCycle method
There are three phases :
1. Mounting
2. Updating
3. Unmounting
Mounting phase lifecycle in-class component in react js with example
In React class components, the mounting phase is the initial phase where the component is created and added to the DOM. During the mounting phase, the following lifecycle methods are called in the order listed below:
constructor(props)
- This method is called first and initializes the component's state and binds class methods.
static getDerivedStateFromProps(props, state)
- This method is called after the constructor and before the render method. It allows the component to update its state based on changes in props.
render()
- This method is called next and returns the JSX that defines the component's UI.
componentDidMount()
- This method is called after the component has been rendered to the DOM. It's used for any side effects, like fetching data from an API or setting up event listeners.
Here's an example of a class component with the mounting phase lifecycle methods:
class MyComponent extends React. Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this);
}
static getDerivedStateFromProps(props, state) {
// update state based on props
return null;
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>My Component</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Click me</button>
</div>
);
}
componentDidMount() {
// setup side effects
}
}
In this example, the constructor
initializes the component's state and binds the handleClick
method to the component instance. The getDerivedStateFromProps
method is not used and simply returns null.
The render
method returns JSX that includes a button
element with an onClick
handler that calls the handleClick
method to update the component's state.
Finally, the componentDidMount
method is called afte