Understanding React Lifecycles: A Deep Dive with Real-World Examples🥳
React lifecycles! React lifecycles can be a bit overwhelming, especially for beginners, but worry not! We'll break it down step-by-step and provide you with real-world examples to help you grasp the concepts better.
What are React Lifecycles?
In React, components have a lifecycle that represents the different stages a component goes through from its creation to its removal from the DOM. Each stage offers specific lifecycle methods that allow us to perform actions at certain points during a component's existence.
React lifecycles are categorized into three main phases:
- Mounting Phase:
This phase occurs when a new component is being created and inserted into the DOM. It happens when the component is initially rendered.
Key Lifecycle Methods in the Mounting Phase:
constructor()
: This is the first method called when a component is instantiated. It is used to set up the component's initial state and bind event handlers.render()
: This is a required method that returns the JSX representation of the component's UI. It should be a pure function, meaning it should not modify the component state.componentDidMount()
: This method is called immediately after the component is added to the DOM. It's an excellent place to start timers, fetch data from an API, or perform any other actions that require the component to be fully mounted.
- Updating Phase:
The updating phase is triggered when a component's state or props change, and the component needs to be re-rendered to reflect those changes.
Key Lifecycle Methods in the Updating Phase:
shouldComponentUpdate()
: This method is invoked before the component is re-rendered. It allows you to control whether the component should update or not. By default, it returnstrue
, meaning the component will update. You can optimize performance by implementing your logic here.render()
: As mentioned earlier, this method returns the updated JSX representation of the component's UI.componentDidUpdate()
: This method is called after the component's updates are flushed to the DOM. It is suitable for performing side effects, like updating the DOM or making additional API calls.
Unmounting Phase:
This phase is triggered when a component is being removed from the DOM.
Key Lifecycle Method in the Unmounting Phase:
componentWillUnmount()
: This method is called right before the component is removed from the DOM. It is the ideal place to clean up any resources, such as clearing intervals, canceling API requests, or removing event listeners to avoid memory leaks.
Intuitive Example: A Timer Component
Let's build a Timer component to see these lifecycle methods in action. The Timer will display the elapsed time since it was mounted and update every second.
import React, { Component } from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState((prevState) => ({ seconds: prevState.seconds + 1 }));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
<h1>Timer Example</h1>
<p>Elapsed Time: {this.state.seconds} seconds</p>
</div>
);
}
}
export default Timer;
Explanation:
Mounting Phase:
The Timer component's constructor is called first, where we set the initial state, initializing the
seconds
to 0.After the constructor, the
render()
method is called to create the component's UI. At this point, the Timer is mounted but not yet added to the DOM.Once the render is complete,
componentDidMount()
is invoked. In our example, we use this method to start an interval that updates the state'sseconds
every second. This interval continues until the component is unmounted.
Updating Phase:
In our example, there are no specific updates to the component's state or props. However, if there were updates, React would call the
shouldComponentUpdate()
method to determine if the component should update. If it returnstrue
, the component would re-render, and therender()
method would be called again.After re-rendering,
componentDidUpdate()
would be called, allowing us to perform any additional side effects after the update is flushed to the DOM.
Unmounting Phase:
- When the Timer component is removed from the DOM,
componentWillUnmount()
is called. In our example, we use this method to clear the interval we set up during the mounting phase. This ensures that we avoid any potential memory leaks after the Timer is no longer needed.
- When the Timer component is removed from the DOM,
Conclusion
Congratulations! You've now delved into the depths of React lifecycles. Understanding these lifecycles is crucial for managing component behavior and side effects properly. Remember that with the advent of functional components and hooks, the traditional lifecycle methods may not be used as frequently. However, learning them will give you a solid foundation to work with React, and you'll be better equipped to understand the newer concepts as well.
Keep practicing and building more components to reinforce your understanding. React is an incredibly powerful library, and mastering its lifecycles will help you create efficient and performant applications. Happy coding and may your React journey be smooth and enjoyable! 🚀
Stay Curious! 😍❤️🔥
Subscribe to my newsletter
Read articles from Rakesh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by