Lifecycle methods in ReactJS

Author Purushothaman Raju ,Posted on May 23 2020

Lifecycle methods simply are pieces of code that is executed during a specific timeline of a component. for example before rendering, A component logic can be added to either fetch some data from an API or we can decide to add or remove className of elements based on the prop.

React has the following lifecycle methods to help us add logic to the component. Do remember that these lifecycle methods are only applicable to class-based components and not functional components.

  1. Constructor
    This is the very first method that is executed. I’m sure many would be aware of a constructor since it’s from the OOPS world.
    In React we usually use a constructor to initialize state and in some cases to make API calls and store it on the state. the constructor is only called once during the entire timeline of the component.

  2. Render
    Another very important method for class-based components which defines which UI or JSX we intend to show to the user. This is called every time there is a change in component state.

  3. ComponentDidMount
    This is method is called only once right after the render method gets called for the first time. We usually make API calls in this method and store it on the state.

  4. ShouldComponentUpdate
    Every time there is a state change componentShouldUpdate is called if we return false inside this method component will not be rendered.

  5. ComponentDidUpdate
    Every time there is a state change componentDidUpdate method is called, Be careful not to call the setState() method inside componentDidupdate it will result in an infinite loop.

  6. ComponentWillUnmount
    This method is also called only once and it is always at the end of component timeline or lifecycle. This method is usually used to clear any pending promises to avoid a memory leak.
class App extends React.Component{
    
    constructor(props) { 
        super(props);
        console.log('I will be inoked first ')
    }

    componentDidMount() {
        console.log('I will be invoked only once and right after the first render() method invocation')
    }

    shouldComponentUpdate() { 
        console.log('I will triggered everytime there is a change in state')
    }

    componentDidUpdate() { 
        console.log('I will triggered everytime there is a change in state')
    }

    componentWillMount() {
        console.log('I will be triggered when the component unmounts')
    }

    
    render() {
        console.log('I will be invoked second and everytime there is change in state')
        return (<h1>My Component</h1>)
    }
}

More information on life cycle methods is available on react documentation site feel free to check it out.