Introduction to React Component Lifecycle
The React Component Lifecycle refers to the series of methods that are invoked in the process of creating, updating, and destroying a component in a React application.
These methods allow the component to perform certain actions at specific points in its lifecycle.
Understanding the React Component Lifecycle is important for building robust and efficient applications in React.
Constructor
The first method that is invoked in the lifecycle of a component is the constructor method. This method is called when the component is being created and is used to initialize the component's state and bind event handlers.
JAVASCRIPT
1// Example code related to constructor method
2
3class MyComponent extends React.Component {
4 constructor() {
5 super();
6 this.state = {
7 count: 0
8 };
9 }
10
11 render() {
12 return (
13 <div>
14 <h1>Counter: {this.state.count}</h1>
15 <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
16 </div>
17 );
18 }
19}
xxxxxxxxxx
33
ReactDOM.render(<MyComponent />, document.getElementById('root'));
// Example code related to React Component Lifecycle
class MyComponent extends React.Component {
constructor() {
super();
this.state = {
count: 0
};
}
componentDidMount() {
console.log('Component is mounted');
}
componentDidUpdate() {
console.log('Component is updated');
}
componentWillUnmount() {
console.log('Component is unmounted');
}
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
</div>
);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment