Yogesh Chauhan's Blog

How to add Lifecycle Methods to a Class in React?

in React on April 26, 2021

Let’s catch up what we’ve done so far.

We saw earlier in this Components and Props in React post that you can declare the components in two different ways. No matter which method you use to do so, one thing is clear. It must not modify its props.

That’s where the states concept comes into play.

So, we learned How to convert a function component into a class in React?

Then, we went through the steps on How to add Local State to a Class in React?

Now, it’s time to add Lifecycle Methods.

When any element is rendered to the DOM for the first time, it’s called “mounting” and when it’s removed from the DOM, it’s called “unmounting”.

We need to add some code to run when those events occur. Thankfully, React has a solution.

React has special methods such as componentDidMount and componentWillUnmount for those events. Those are called “lifecycle methods”.

We can use componentDidMount method to start the timer using setInterval:



componentDidMount() {
  this.timerID = setInterval(
     () => this.tick(),
     1000
  );
}


The code above will run after the component is rendered to the DOM.

We have saved the setInterval function into a variable since it’ll be needed to clear the timer later on.

And we can use componentWillUnmount to clear the variable:



componentWillUnmount() {
    clearInterval(this.timerID);
}


That’s it we just added the lifecycle methods.

What happens next to this whole process? Find out in this post: How states work in React?


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Classes in JavaScript: The BasicsJavaScriptHow can one check to see if a remote file exists using PHP?PHPIntroduction to components and templates Part 1: Component MetadataAngularAlternate Style Sheets in CSSCSSWhat’s the difference between visibility: hidden and display: none?CSSWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQuery