LIfe of a React Component: The Lifecycle Methods

Understanding the lifecycle of a react component is very crucial. It enables you to write code at a certain point in the process. There are basically four important lifecycle methods: componentDidMount, componentDidupdate, componentWillUnmount, shouldComponentUpdate. Let’s look at these methods in detail.

ComponentDidMount

componentDidMount is a method that is invoked when the react component is mounted to the DOM. If you need to perform operations like fetching data or setting initial states for different components it is advised to perform such operations in this function. You can’t update initital states in the component after it has been mounted else it will cause infinite loop.

ComponentDidUpdate

This is the function called just after the component is updated. When you first load a react component componentDidMount is called and after that with every update componentDidUpdate is called. You can access DOM in this function and mostly any code that interacts with DOM elements is written here. You can also setup setState in this method but with a condition else it will cause a infinite loop.

ShouldComponentUpdate

shouldComponentUpdate is a method that allows you to alter the updating mechanism of react component. The function returns true by default which leads to normal execution but if you return false it will skip a particular update to the component. You might use this to skip component updates for certain props or state values which you feel aren’t important to update. But it should always be used with caution because if it is not executed properly it can lead to bugs.

ComponentWillUnmount

This is a method called when the component is remove from DOM. This method is basically used for certain cleanups. setState shouldn’t be called in this method because it will never be called.

These are the important lifecycle methods but there are new methods that React team has introduced in recent updates. I would like you to go through the docs to know all these functions.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.