What are lifecycle methods in React?
React's component-based architecture enables us to develop reusable and interactive user interface components. It provides lifecycle methods as part of this system, allowing us to do specified activities at various stages of a component's existence.
React lifecycle methods
React lifecycle methods are predefined functions that are called at various phases of a React component's lifecycle. These methods enable us to do specified actions such as initialization, rendering, updating, cleanup, and handling events at various stages of a component's life cycle, from creation to removal from the DOM.
Each React component has a lifecycle that you can observe and manage through its three major phases. The three phases are:
Component mounting: birth of your component
Component updating: growth of your component
Component unmounting: death of your component
Component mounting
The mounting phase begins when a component is about to be rendered and inserted into the DOM. During this phase, the 3 lifecycle methods are invoked i.e. constructor() , render() , componentDidMount().
You can modify the component state within the
componentDidMount()method, but it should be done with caution to avoid performance issues.
Constuctor()
When a component is formed, constructor() is the first method that is called. It sets the state of the component and binds event handlers.
Example
class MyComponent extends React.Component {constructor(props) {super(props);this.state = {count: 0};}// ...}
Render()
Render() method is responsible for rendering the component's JSX representation onto the screen. It returns the JSX code that describes what should be displayed.
Example
class MyComponent extends React.Component {render() {return (<div><h1>Hello, React!</h1></div>);}// ...}
ComponentDidMount()
ComponentDidMount() method is called immediately after the component is mounted in the DOM. It is commonly used for fetching data from APIs or setting up subscriptions.
Example
class MyComponent extends React.Component {componentDidMount() {// Fetch data from an APIfetch('https://api.example.com/data').then(response => response.json()).then(data => {// Update component state with fetched datathis.setState({ data });});}// ...}
Component updating
The updating phase occurs when a component's state or props change. The lifecycle methods involved in this phase are shouldComponentUpdate(), render(),componentDidUpdate().
You can modify the component state within the
componentDidUpdate()method, but it should be done with caution to avoid performance issues.
ShouldComponentUpdate()
ShouldComponentUpdate() method is called before the component is updated, allowing us to optimize performance by determining whether the component should re-render or not. It returns a boolean value.
Example
class MyComponent extends React.Component {shouldComponentUpdate(nextProps, nextState) {// Perform custom logic to decide whether to re-render or notif (this.props.value === nextProps.value) {return false; // Do not re-render}return true; // Re-render}// ...}
ComponentDidUpdate()
componentDidUpdate() method is called immediately after the component is updated in the DOM. It is commonly used for performing side effects or updating the DOM based on new props or states.
Example
class MyComponent extends React.Component {componentDidUpdate(prevProps, prevState) {// Perform side effects or update the DOMif (this.props.isOpen !== prevProps.isOpen) {// Toggle a modal or update a UI element// ...}}// ...}
Component unmounting
The unmounting phase occurs when a component is about to be removed from the DOM. The lifecycle method involved in this phase is componentWillUnmount().
You cannot modify the component state within the
componentWillUnmount()method
ComponentWillUnmount()
componentWillUnmount() method is called just before a component is unmounted. It allows us to perform necessary cleanup tasks, such as removing event listeners or canceling subscriptions, to avoid memory leaks.
Example
class MyComponent extends React.Component {componentWillUnmount() {// Clean up resources, such as event listeners or subscriptionswindow.removeEventListener('scroll', this.handleScroll);}// ...}
Implementation
To understand these lifecycle methods better, let's create a to-do list application.
To-do list application
Let's build a to-do list application that allows users to add, update, and remove tasks. We will use lifecycle methods to fetch initial data from an API in componentDidMount(), update tasks based on user interactions in componentDidUpdate(), and clean up resources in componentWillUnmount().
Explanation
Let's go through the different stages of the React lifecycle and how they relate to our to-do list application.
Mounting phase
constructor(): TheTodoAppcomponent's constructor is called when the component is initialized. In our application code, we set the initial state,tasks, to an empty array.render(): Therender()method is responsible for rendering the JSX representation of the component. It returns the HTML elements, including theTodoFormandTodoListcomponents, along with the current list of tasks.componentDidMount(): This lifecycle method is invoked after the component is inserted into the DOM. In this case, we don't have any specific action to perform, so we don't include it in our example.
Updating phase
shouldComponentUpdate(): This method is not explicitly defined in our example. React automatically performs a shallow comparison of state and props to determine if the component needs to re-render. If any changes occur, the component will update.render(): Therender()method is invoked again when the component is updated, reflecting any changes in the state. It re-renders theTodoFormandTodoListcomponents with the updated list of tasks.componentDidUpdate(): We don't use this method in our example. It is typically used for performing side effects after a component update, such as making additional API calls or interacting with the DOM.
Unmounting phase
componentWillUnmount(): Since our application doesn't have a specific component unmounting event, we don't include this method in our example. It is commonly used to clean up resources like event listeners or subscriptions before the component is removed from the DOM.
Conclusion
Understanding and utilizing React's lifecycle methods is essential for developing robust and efficient apps. The componentDidMount(), componentDidUpdate(), and componentWillUnmount() methods handle the three most important steps of a component's lifecycle: mounting, updating, and unmounting. By using these methods effectively, we can manage data fetching, perform side effects, and ensure proper resource cleanup.
Free Resources