DEV Community

Yeasin Arafat
Yeasin Arafat

Posted on

Understand to Easy React Component Lifecycle

React component lifecycle going through three ways which are mounting, updating, unmounting.
Mounting:- it represents the rendering of the component in the DOM node.
Updating:- it represents the re-rendering of the component in the DOM node.
Unmounting:- it represents the removal of the React component.

React life-cycle Methods
render()
it renders components in the virtual DOM instance. it happens when mounting & updating of the component in the DOM tree. A render() method has to be pure with no side-effects. c
componentDidMount()
It is a good place to call API endpoints and to do network requests. In our clock component, setInterval function can be set here to update the state (current date and time) for every second. it Invoked after the initial mounting of the component in the DOM tree.

componentDidUpdate()
looks like Similar to ComponentDidMount() but invoked during the update phase. Network request can be done during this phase but only when there is difference in component’s current and previous properties.

componentWillUnmount()
it is invoked after the component is unmounted from the DOM. This is the good place to clean up the object. In our clock example, we can stop updating the date and time in this phase.

shouldComponentUpdate()
it is invoked during the update phase. Used to specify whether the component should update or not. If it returns false, then the update will not happen.

getDerivedStateFromProps ()
it is invoked during both initial and update phases and just before the render() method. It returns the new state object. It is rarely used where the changes in properties result in state change. It is mostly used in animation contexts where the various states of the component are needed to do smooth animation.

getSnapshotBeforeUpdate()
it is invoked just before the rendered content is committed to the DOM tree. It is mainly used to get some information about the new content. The data returned by this method will be passed to componentDidUpdate() method. For example, it is used to maintain the user’s scroll position in the newly generated content. It returns the user's scroll position. This scroll position is used by componentDidUpdate() to set the scroll position of the output in the actual DOM.

Image description

Top comments (0)