0% found this document useful (0 votes)
41 views16 pages

Understanding React Component Lifecycle

The document discusses the different lifecycle methods in React components including mounting, updating, and unmounting. It covers constructor, render, componentDidMount, getDerivedStateFromProps, shouldComponentUpdate, componentDidUpdate, and componentWillUnmount methods and describes what occurs in each phase and the order methods are called.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views16 pages

Understanding React Component Lifecycle

The document discusses the different lifecycle methods in React components including mounting, updating, and unmounting. It covers constructor, render, componentDidMount, getDerivedStateFromProps, shouldComponentUpdate, componentDidUpdate, and componentWillUnmount methods and describes what occurs in each phase and the order methods are called.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lifecycle methods in React

Topics covered:
● What is the life cycle of a component?
● Mounting
○ constructor()
○ getDrivedStateFromProps()
○ render()
○ componentDidMount()
● Update
○ getDerivedStateFromProps()
○ shouldComponentUpdate()
○ render()
○ getSnapshotBeforeUpdate()
○ componentDidUpdate()
● Unmounting
○ componentWillUnmount()

1. Lifecycle of a component:

The three major phases of each component's lifecycle in React can be used to monitor and
modify each component.

It consists of three stages:

● Mounting (Inserting element in DOM)


● Updating (Modifying element in DOM)
● Unmounting (Removing element from DOM)

These represent the beginning, development, and ending of a component, respectively.

1
2. Mounting

When a React component is generated and added to the DOM, we can view it on the
user interface or in the browser;

it goes through the following processes, listed here in the order they occur:

● Constructor.
● static getDerivedStateFromProps()
● render()
● componentDidMount()

constructor:

When the component is started, the Constructor() method is the first function that is
executed, making it the obvious place to set up the initial state and other basic settings.

You should always use the super(props) method before any other method in order to
start the parent's constructor procedure and allow the component to inherit methods
from its parent. The Constructor() method is invoked with the props as arguments
([Link]).

2
getDerivedStateFromProps():

The second method that is called, both on the initial mount and future updates, is
getDerivedStateFromProps().

● It is called just before invoking the render method.


● If the state needs to be updated, it must return an object; otherwise, it must return null.
● It is not frequently used and is only used when state derivation is necessary.

3
Output:

Render method

The third method is called render, and it is the only one that is absolutely necessary to render
our class component.

It is called anytime there is a change in state or props, and it is largely used for printing the JSX
in DOM.

Class Header extends Component{

render(

4
//JSX

<[Link]>

<h1>Hello JavaScript Users </h1>

</[Link]>

)
}

componentDidMount():

The final lifecycle method in the mounting stage, componentDidMount(), is called right away
when a component is put into the DOM.

It is mostly used for making API calls and is only called once.

5
This will be the output before 1000 milliseconds:

This will be the output after 1000 millisecond:

3. Updating:

The next stage in the lifecycle occurs when a component is updated.


Every time a component's state or props change, the component is updated.
When a component is changed, React's five built-in methods are called in the following order:

● static getDerivedStateFromProps()
● shouldComponentUpdate()

6
● render()
● getSnapshotBeforeUpdate()
● componentDidUpdate()

The render() method is essential and is always called; the others are optional and are only
called if they are defined.

getDerivedStateFromProps:
● The getDerivedStateFromProps function is also invoked during updates. When a
component is updated, this is the first method that is called.
● This is still the correct location to set the state object based on the initial props.
● Two procedures that are used frequently during the Mounting stage are static
getDerivedStateFromProps and render().

The button in the following example changes the favorite color to green, however because the
getDerivedStateFromProps() function is invoked, which updates the state with the color from the
favcol attribute, the favorite color remains blue:

7
Output:

shouldComponentUpdate:

● The shouldComponentUpdate() method returns a Boolean value indicating whether


React should continue with the rendering or not.
● True is the default value.
● shouldComponentUpdate() is used to inform React whether the current change in state
or props has no impact on a component's output.
● Re-rendering occurs automatically by default whenever a state changes.
● Similar to componentDidMount(), componentDidUpdate() is the final method to be called
during the update phase. It is only called once, and when it is, it indicates that the DOM
has been changed.
● After the DOM has been updated, ComponentDidUpdate() is typically used to operate on
DOM elements.
● The following example illustrates what transpires when the shouldComponentUpdate()
function returns false:

8
In this case, we send the value to shouldComponentUpdate, which returns false.

So, if we click the change color button in the output, there will be no change in the
component because the value returned by shouldComponentUpdate is false.

If we return the true value to shouldComponentUpdate, the component will be updated


when we click the change color button.

9
Output:

10
render():

When a component is updated, it must re-render the HTML to the DOM with the new changes,
which calls the render() method.

The button in the example below switches the favorite color to Green:

Output:

11
getSnapshotBeforeUpdate():

● The getSnapshotBeforeUpdate() method gives you access to the props and state from
before the update, so you can examine the values from before the update even after it
has occurred.
● The componentDidUpdate() function must be present in addition to the
getSnapshotBeforeUpdate() method in order to avoid an error.

Although the example below appears complex, all it accomplishes is the following:
● The preferred color "red" is displayed when the component is mounting.
● After mounting the component, a timer modifies the state, and after one second, the
preferred color switches to "yellow."
● Since this component includes a getSnapshotBeforeUpdate() method, it is called when
the update phase is triggered. This method writes a message to the empty DIV1
element.
● The empty DIV2 element is then written with the following message by the
componentDidUpdate() method:
To see what the state object looked like before the change, use the getSnapshotBeforeUpdate()
method:

12
Output:

componentDidUpdate():

● After the component has been updated in the DOM, the componentDidUpdate function
is called.
● The following example may appear difficult, however it only does the following:
● When the component is mounted, the color "red" is used to represent it.
● A timer changes the state and the color to "blue" after the component is mounted.
● This action initiates the update phase, and because this component includes a
componentDidUpdate function, this method is invoked and a message is written to the
empty DIV element:

13
Output:

14
4. Unmounting:
The final phase of a component's lifecycle, unmounting, marks the end of the component's
existence in the DOM.
● componentWillUnmount() is the main method it contains.
● Before a component is unmounted and destroyed, componentWillUnmount() is called.
● It is mostly used to clean up our code, such as cancelling API calls or removing any
subscriptions generated by componentDidMount ().
● Here is an example of unmounting:

Here is the Output:

15
16

Common questions

Powered by AI

During the updating phase, lifecycle methods are executed in a specific order: getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, and finally componentDidUpdate. Initially, getDerivedStateFromProps updates the state based on new props. shouldComponentUpdate provides control over whether updates affect rendering. If it returns false, the subsequent steps are bypassed. render method then re-renders the component. getSnapshotBeforeUpdate captures previous DOM states before making these changes. Finally, componentDidUpdate performs post-render operations and DOM manipulations. This sequence ensures controlled state management, efficient rendering, and clear post-update actions .

The render method is fundamental as it is responsible for describing the UI components that will be rendered to the DOM. During the mounting phase, render is called to build and display the initial DOM elements of a component. In the updating phase, render is called whenever there is a change in state or props to reflesh the UI with the updated data. It is critical as it ensures the UI accurately reflects the current state, acting as the visual bridge between JavaScript logic and actual DOM updates .

The unmounting phase of a React component lifecycle, specifically through the componentWillUnmount method, allows developers to clean up resources before a component is destroyed. This includes cancelling any active network requests, removing event listeners, or clearing intervals and timeouts used by the component in earlier phases, such as those set up in componentDidMount. Properly managing these operations helps prevent memory leaks and ensures that a component leaves no residual side effects or processes after its lifecycle ends .

The getDerivedStateFromProps method behaves similarly in both the mounting and updating stages by deriving and updating the state based on the props provided. During mounting, it's called just before render() to set the initial state based on props. In the updating stage, it's also the first method called but used for updating the state when props change. In both cases, if state needs updating, it must return an object; otherwise, return null .

The componentDidMount method is crucial because it is invoked immediately after a component is added to the DOM and is commonly used to perform operations like API calls, especially ones that interact with real-time data. Unlike other mounting methods such as constructor or getDerivedStateFromProps, componentDidMount is the final method called in the mounting phase and is designed for operations that require DOM nodes, as it guarantees the component is present in the DOM .

The getDerivedStateFromProps method is advisable in scenarios where the component's state needs to be directly synchronized with changes in props, as it gets called every time props change, not just on mount. This could be particularly useful when deriving state from complex props or when managing state propagation in controlled components. Unlike constructor, getDerivedStateFromProps offers deterministic execution before rendering on updates, making it more suitable for dynamic synchronization, whereas componentDidMount doesn't get called on updates and is more suited for initialization tasks like data fetching .

The getSnapshotBeforeUpdate method allows React components to capture information from the DOM before it is potentially changed and updated. This method is particularly useful for capturing the scroll position or other DOM attributes prior to rendering. Any value returned by this method is passed as an argument to componentDidUpdate, allowing developers to perform necessary operations with the previous state data after the DOM has been updated. This close interaction with componentDidUpdate enables synchronization between the virtual DOM's previous and current state .

The lifecycle of a React component consists of three main stages: Mounting, Updating, and Unmounting. The Mounting stage is responsible for creating and inserting DOM elements; it includes methods like constructor(), getDerivedStateFromProps(), render(), and componentDidMount(). The Updating stage manages re-rendering of components when state or props change, with methods like getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), and componentDidUpdate(). Finally, the Unmounting stage involves removing elements from the DOM, specifically using the componentWillUnmount() method. These phases allow developers to manage how components are inserted, updated, and removed from the DOM effectively, ensuring proper resource management and UI behavior .

The shouldComponentUpdate method determines whether the render process should occur when there is a change in state or props, returning a Boolean to indicate this decision. If it returns false, React skips rendering and updating DOM elements. Conversely, if it returns true, rendering proceeds, and once updates are made to the DOM, the componentDidUpdate method is called to perform post-update operations. Thus, shouldComponentUpdate provides a fine control over unnecessary rendering, while componentDidUpdate allows side-effect handling post-update, such as dealing with the DOM or making network requests .

When implementing componentWillUnmount, developers should consider cleaning up all resources and subscriptions that were set up in componentDidMount or elsewhere, such as removing event listeners or clearing timers. It is also important to ensure any asynchronous tasks are properly cancelled to prevent side effects like memory leaks. Additionally, developers should avoid setting state in this method as the component will soon be removed from the DOM, making state updates irrelevant .

You might also like