Component Lifecycle
- Mounting Phase:
- constructor( ): Initializes state and binds event handlers.
- render( ): Renders the component’s UI based on initial state/props.
- componentDidMount( ): Executes after component insertion, ideal for initial setup and data fetching.
- Updating Phase:
- shouldComponentUpdate( ): Determines if the component should re-render.
- render( ): Updates the UI based on state/props changes.
- componentDidUpdate( ): Executes after component updates, useful for side effects based on new data.
- Unmounting Phase:
- componentWillUnmount( ): Executes just before component removal, used for cleanup tasks to prevent memory leaks.
Example: This example shows the use of all component lifecycle methods in one code example.
import React, { Component } from 'react';
class LifecycleExample extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
console.log('Constructor called');
}
componentDidMount() {
console.log('Component did mount');
}
componentDidUpdate() {
console.log('Component did update');
}
componentWillUnmount() {
console.log('Component will unmount');
}
handleIncrement = () => {
this.setState(
(prevState) => ({ count: prevState.count + 1 }));
};
render() {
console.log('Render method called');
return (
<div>
<h1>Lifecycle Example</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.handleIncrement}>
Increment
</button>
</div>
);
}
}
export default LifecycleExample;
Output:
Getting Started with React
ReactJS, often referred to as React, is a popular JavaScript library developed by Facebook for building user interfaces. It emphasizes a component-based architecture, where UIs are built using reusable components. React uses a declarative syntax to describe how UIs should look based on their state, simplifying development and enhancing code readability.
React also utilizes a virtual DOM to optimize rendering performance by minimizing actual DOM manipulations. React’s unidirectional data flow and rich ecosystem of libraries and tools have made it a go-to choice for frontend development, especially in building single-page applications (SPAs).
Table of Content
- Why ReactJS ?
- Setting Up Your Development Environment
- Understanding React Components
- Creating Your First React Component
- JSX (JavaScript XML)
- Working with Props and State
- Handling Events:
- Conditional Rendering
- Lists and Keys
- Styling React Components
- Introduction to React Hooks
- Building a Simple React Application
- Component Lifecycle
- React Router
- Managing State with Context API