React Lifecycle Methods
The various phases in the lifecycle of React components are known as React lifecycle methods. It consists of three main phases, i.e., mounting, updating, and unmounting. The developers use lifecycle methods to control the behavior of the components at the different stages. It also helps them create interactive user interfaces.
The lifecycle method in React starts with the mounting phase when a component is created. Then continues to the updating phase when the component’s state changes, until the final and last stage, which is an unmounting phase. In this blog, we will look at the different stages of React lifecycle methods. We will also explore how the lifecycle method in React works.
Mounting
Mounting is the first phase of lifecycle method in React. It is the process of creating a component and mounting it into the DOM (Document Object Model). There are four in-built methods called in a specific order when mounting a component.
The following are those four methods:
- constructor(): It is the first method called after a component is created. It is used to initialize the state of the components and bind methods. The method is called with the props every time the developer creates a new component.
For example,
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.increment = this.increment.bind(this);
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById(‘root’));
Also Read: React Projects Ideas
- getDerivedStateFromProps(): This method is used to update the state based on changes in props. It is called after the constructor method, right before the elements in the DOM are rendered.
For example,
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = { username: “” };
}
static getDerivedStateFromProps(props, state) {
if (props.user) {
return { username: props.user.username };
}
return null;
}
render() {
return (
<div>
<h1>User Profile: {this.state.username}</h1>
<p>Name: {this.props.user.name}</p>
<p>Email: {this.props.user.email}</p>
</div>
);
}
}
const user = { name: “John”, email: “john@example.com”, username: “johnny” };
ReactDOM.render(<UserProfile user={user} />, document.getElementById(‘root’));
- render(): This method does not modify the component’s state or interact with the outside world. It is a pure function. It is called to generate the HTML representation of the component. This method is required and is always called, unlike the other options.
For example,
class MyElement extends React.Element {
constructor(props) {
super(props);
this.state = {
name: “John”
};
}
render() {
return (
Hello, {this.state.name}!
);
}
}
- componentDidMount(): This method is used to fetch data from an API, add event listeners, or start animations. It is called after the component is added to the DOM.
For Example,
class TodoList extends React.Component {
constructor(props) {
super(props);
this.state = { todos: [] };
}
componentDidMount() {
fetch(“https://jsonplaceholder.typicode.com/todos”)
.then(response => response.json())
.then(data => {
this.setState({ todos: data });
});
}
render() {
return (
<div>
<h1>Todo List</h1>
<ul>
{this.state.todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<TodoList />, document.getElementById(‘root’))
Updating
This phase in React lifecycle methods is applied when a component is updated. It is updated whenever there is a change in the state or props of the component. React has five in-built methods that are called in a specific order during this phase.
The following are those five methods:
- getDerivedStateFromProps(): This method is the first to be called when a component is updated. It sets the state object based on the initial props.
For example,
class User extends React.Component {
constructor(props) {
super(props);
this.state = {
name: props.name,
email: props.email
};
}
static getDerivedStateFromProps(props, state) {
if (props.name !== state.name || props.email !== state.email) {
return {
name: props.name,
email: props.email
};
}
return null;
}
render() {
return (
<div>
<h1>{this.state.name}</h1>
<p>{this.state.email}</p>
</div>
);
}
}
ReactDOM.render(<User name=”John Doe” email=”john.doe@example.com” />, document.getElementById(‘root’));
- shouldComponentUpdate(): This method allows the developer to compare the current state and props with the next state and props. It decides if the component should update. It is also called before rendering when new state and props are received.
For Example,
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.count % 3 === 0) {
return true;
}
return false;
}
handleClick = () => {
this.setState((prevState) => ({
count: prevState.count + 1
}));
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById(‘root’));
- render(): This lifecycle method in React is called to render the components based on the updated state and props.
For Example,
class Greeting extends React.Component {
constructor(props) {
super(props);
this.state = {
name: props.name
};
}
handleChange = (event) => {
this.setState({ name: event.target.value });
};
render() {
return (
<div>
<h1>Hello, {this.state.name}!</h1>
<input type=”text” value={this.state.name} onChange={this.handleChange} />
</div>
);
}
}
ReactDOM.render(<Greeting name=”John” />, document.getElementById(‘root’));
Also Read: What is React JS?
- getSnapshotBeforeUpdate(): This method gives access to the state and props before the update. This means even after the update, the developer can check the values before the update.
For Example,
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date()
};
this.timerID = null;
}
componentDidMount() {
this.timerID = setInterval(() => {
this.setState({ time: new Date() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
return { prevTime: prevState.time };
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot.prevTime !== this.state.time) {
console.log(‘Time updated!’);
}
}
render() {
return (
<div>
<p>{this.state.time.toLocaleTimeString()}</p>
</div>
);
}
}
ReactDOM.render(<Timer />, document.getElementById(‘root’));
- componentDidUpdate(): This method performs any required cleanup. It is called after the component has been updated and the new state and props have been rendered.
For Example,
class TodoList extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: [
{ id: 1, text: ‘Learn React’ },
{ id: 2, text: ‘Build an app’ }
]
};
}
handleClick = () => {
const newTodo = { id: 3, text: ‘Deploy app’ };
this.setState((prevState) => ({
todos: […prevState.todos, newTodo]
}));
};
componentDidUpdate(prevProps, prevState) {
if (prevState.todos.length !== this
ReactDOM.render(<Header />, document.getElementById(‘root’));
Unmounting
This is the final phase of lifecycle method in React. It is the process of removing the component from the DOM. You can learn more about ReactJS through this comprehensive React JS Course.
There are two in-built methods in the unmounting phase. The following are those:
- componentWillUnmount(): This method is used to clean any resources that were created when the component was being mounted. It is called right before the component is removed from the DOM. For Example,
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
componentDidMount() {
console.log(“The component named Container has been mounted.”);
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type=”button” onClick={this.delHeader}>Delete Header</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert(“The component named Child is about to be unmounted.”);
}
componentDidMount() {
console.log(“The component named Child has been mounted.”);
}
render() {
return (
<h1>Hello!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById(‘root’));
- componentDidMount(): This method is used for the final clean-up and is called after the component has been removed from the DOM. It is not a standard lifecycle method in React but a naming convention used by some developers. For example,
class MyComponent extends React.Component {
componentWillUnmount() {
// Clean up any resources here
}
render() {
return (
// JSX for component here
)
}
}
Here, the componentWillUnmount() method is defined to clean up any resources when the component is unmounted. While the render method is where the JSX for the component is defined.
Conclusion
Understanding the React lifecycle methods is essential for building efficient and robust React applications. The developer has access to several methods that allows them to perform specific tasks at each stage. In order to master the lifecycle methods of React, one must have scalable and sufficient knowledge of React.