DEV Community

Abdur Rahman
Abdur Rahman

Posted on

An introduction to React component lifecycle

To understand how a component in a React application is rendered, we need to first understand how the component lifecycle works. There are 3 phases in the component lifecycle –
• Mounting
• Updating
• Unmounting

Mounting

Mounting is the phase when the component is mounted on the DOM. In this phase the component is rendered on the webpage for the first time. There are 2 main functions in this phase –
componentWillMountI(): This function is called before render() function is called. This indicates that the component has been initialized and now ready to be mounted.
componentDidMount(): This function is called after the render() function is called thus the webpage has been loaded for the first time.
Updating
In this stage the props and state are passed down or updated then the whole webpage re-renders based on the props and states. So, in this stage the webpage might be rendered based on the cookies or based on the user preferences. One of the most common examples can be some users want to load their webpage in dark mode and some might want it to load in light mode. So, in this stage that data is passed to the component and the component is rendered based on it. There are a couple of functions which are called in this phase of the lifecycle –
componentWillReceiveProps(): In this stage the props is checked. When initially loading a component for the first time, default props are given. So, in this stage the props are checked again to see if anything is changed.
setState(): With this function the state is changed. This is not mandatory as many components might not have a state. So, if there is any state that needs to be updated is updated so that the component can re-render.
shouldComponentUpdate(): This checks the given props and states if anything has changed. So, after checking it the component gets ready to update itself if necessary.
componentWillUpdate(): So, if the component is needed an update and another render then this function is called.
componentDidUpdate(): After re-rendering the component this function is called to confirm that the webpage has been updated. So, this function is called after render() function and done executing.

Unmounting

As the name suggests, in this phase the component has finished mounting and then updating as necessary and all work is finished. So, it will now unmount from the DOM. Function called in this phase –
• componentWillUnmount(): This function is called to end the lifecycle of a React component. So, with this function the component is unmounted from the DOM.
So, following these specific phases a React component runs on the web browser and completes its lifecycle. It is important for every web developers using React to know about these basic concept if they want to create a website using React. I hope simple guide helps beginners learn about the lifecycle of a React component.

Top comments (0)