We will look into lifecycle methods in react. In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.
We can add some code when a components mounts and unmounts.
shouldComponentUpdate – allows the developer to prevent unnecessary re-rendering of a component by returning false if a render is not required.
mounting – means when a component is rendered for the first time.
unmounting – means when the DOM produced by the component is removed.
render – is the most important lifecycle method and the only required one in any component. It is usually called every time the component’s state is updated, which should be reflected in the user interface.
These methods are called “lifecycle methods”.
Example
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {name: "John"};
}
componentDidMount() {
// do something
}
componentWillUnmount() {
// do something
}
render() {
return (
<div>
<h1>Hello, {this.state.name}!</h1>
</div>
);
}
}
Summary
In this article, we learnt about lifecycle methods of react.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !