Understanding ReactJS lifecycle methods

The React lifecycle method helps us in adding logic during different phases of component rendering.
Let us look at the various lifecyle methods of ReactJS and understand when they will be triggered during the component render.

Do remember that the below listed lifecycle methods is only applicable to class based components and not for functional components.


  1. constructor()
    This is the first method that is triggered during the component's lifecycle, this method is usually used to initialize state or to make API calls before showing it to the user also note that
    this method is called only once during the entire lifecycle of the component.

  2. render()
     This is the most important method of class component. If we fail to write this method react will thrown an error it is a must have method in any class component this method primary purpose is to return the UI or the JSX we plan to render on the browser. This method is triggered after the constructor call and every time there is a change in the component state.

  3. ComponentDidMount()
    This method is called after the first time invocation of the render method, We will also use this method to make API calls and store them in state do remember that this lifecyle method(i.e ComponentDidMount) will be called only once.

  4. ShouldComponentUpdate()
    This method is also called when there is a state change. if we return false inside this method the component will not be rendered on DOM.

  5. ComponentDidUpdate()
    This method will be called every time there is a change in the component state or any change in the props from the parent component.

  6. ComponentWillUnmount()
    This lifecycle is method called when we switch from the current component to a new component using routes or we conditionally render this component based state. ComponentWillUnmount will also be called just once usually this called to clear any promise calls before switching to another component.

So based on this list above the most commonly used lifecycle methods are constructor, render and ComponentDidMount most of the logic we write will usually be in any one of these methods.

There are also few other lifecycle methods like getDerivedStateFromProps() and getSnapshotBeforeUpdate() more information about these additional methods can be found on react documentation.  

Comments

Check out

CSS Sprites | What are They?

Login form | Using CSS3

Remove Scrollbars from syntaxhighlighter

Adding a button in HTML | styling a button

HTML5 Semantic Tags | What do they mean

How to remove plus and minus characters from input type number

HTML5 | LocalStorage

How CSS3 Works

jQuery Resources | Support and tutorial help