React Lifecycle (1)
React Lifecycle (1)
1. Mounting
The mounting phase refers to the period when a component is being created and inserted into
the DOM.
During this phase, several lifecycle methods are invoked by React to enable the developer to
configure the component, set up any necessary state or event listeners, and perform other
initialization tasks.
The mounting phase has three main lifecycle methods that are called in order:
Example:
Output:
During this phase, React performs a series of cleanup operations to ensure that the component
and its associated resources are properly disposed of.
The unmounting phase is the last stage in the lifecycle of a React component and occurs when
the component is being removed from the DOM tree.
This can happen for various reasons, such as when the component is no longer needed, the
parent component is re-rendered without including the child component, or when the application
is navigating to a different page or view.
componentWillUnmount(): This method is called just before the component is removed from the
DOM. It allows you to perform any necessary cleanup, such as canceling timers, removing event
listeners, or clearing any data structures that were set up during the mounting phase.
After componentWillUnmount() is called, the component is removed from the DOM and all of its
state and props are destroyed.
It's important to note that once a component is unmounted, it cannot be mounted again. If you
need to render the component again, you will need to create a new instance of it.
Here's an example of how you might use the componentWillUnmount() method to perform
cleanup:
Example: app.js
Students.js
Output: