Lifecycle Methods in Class Components
Class components have access to the React lifecycle methods
Lifecycle Method | Description |
---|---|
used to implement server-side logic before the actual rendering happens, such as making an API call to the server | |
allows us to execute the React code when the component is already placed in the DOM (Document Object Model) | |
used to update the state in response to some changes in our props. | |
provides us the control to manipulate our React component just before it receives new props or state values. | |
allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. | |
used to display the component on the UI returned as HTML or JSX components. | |
llows us to execute the React code when the component gets destroyed or unmounted from the DOM. |
These lifecycle functions are called at different stages of the lifecycle and are used for a variety of purposes like changing the state or doing some work (like fetching data from an external API). They are also referred to as lifecycle hooks.
Example: Program to demonstrate the use of lifecycle methods.
// Filename - App.js
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: "Welcome!" };
}
componentWillMount() {
this.setState({
text: "w3wiki",
});
}
render() {
return <h1>{this.state.text}</h1>;
}
}
export default App;
Output:
React Class Components
Class Components are the reusable code blocks or classes that extends the React.Component. React class components are the backbone of most modern web applications built using React JS. In this article, we’ll learn what class components are, their advantages, how to manage the state and events of the application and how to use them effectively.
Table of Content
- What Are React Class Components?
- Class Components Examples
- Advantages of Class Components
- Implementing state in class components
- Passing props in class components
- Lifecycle methods in class components
- Disadvantages of Class Components