In this article, I will talk about the React Lifecycle and some of the corresponding methods. Let’s get started!
React components go through three main phases:
Mounting: when the component attached itself to the DOM, the birth of your component
Updating: when your component is updating, either because of new props or state changes
Unmounting: when the component is removed from the DOM, the death of your component
We’ll start with the lifecycle methods for the mounting phase. The most common lifecycle method is render() because class components in React require them. render() does exactly what it sounds like and it handles the rendering of the component to the UI . It can also take place during the updating phase. One good thing to know is that you cannot set state in a render because it has to be a pure function (a function without any side-effects)!
componentDidMount() happens when, you guessed it, the component is mounted and is called after the render(). In other words, by the time componentDidMount() is called, the component has been rendered once. Initiating API calls is commonly done in componentDidMount() because it prevents unnecessary re-rendering. But why would you make an API call after the render()? That brings up a good point to tell you that React lifecycle methods are async, meaning that the next method will execute immediately after the previous one, whether the previous one is completed or not. You can set state in componentDidMount() and while it causes an extra rendering, the user does not see this because it will happen before the browser updates the screen (although it could cause some performance issues).
Like I mentioned above, render() also happens in the updating phase.
componentDidUpdate() is called immediately after updating. This method is commonly used to update the DOM with state or prop changes. You can set state here but it MUST be wrapped in a condition, otherwise it’ll cause an infinite loop.
componentWillUnmount() is called before the component is unmounted and removed from the DOM. This method is generally used for cleanup actions (such as invalidating timers or cancelling API calls). You cannot set state in componentWillUnmount() because once a component instance is unmounted, it will not be mounted again therefore it will not re-render.
If you’re a React Hooks kind of guy/gal like I am, the useEffect hook is like a combination of componentDidMount(), componentDidUpdate(), and componentWillUnmount().
Here is a super handy lifecycle diagram from the React docs! Hope you enjoyed the read and see you next time!