React components go through a lifecycle consisting of three main phases: Mounting, Updating, and Unmounting. React allows us to monitor and perform specific actions during these phases. This helps us to manage the component's behavior and interactions with the DOM.
Mounting: The Mounting phase is the initial phase of a component's lifecycle. It occurs when a component is created and inserted into the DOM for the first time.
Updating: The Updating phase occurs when a component receives new props or updates its state, causing the component to re-render. This phase is essential for reflecting changes in the user interface.
Unmounting: This is the third and final phase of a component's lifecycle. It occurs when a component is removed from the DOM.
To understand the concept of component lifecycle, let’s look at an example where we are conditionally rendering the Counter
component within the App
component based on the isCounterVisible
state variable. Clicking the Mount Counter
button toggles isCounterVisible
, displaying the Counter
component if it's true
. Users can increase the count with the Increase count
button. Clicking Unmount Counter
removes it from the DOM tree.
Rerendering vs Remounting
Rerendering is the process that occurs when a component updates its output due to changes in its state or props, triggering the component to execute its rendering logic again.
For example, consider a real-time news feed where new articles are fetched and added to the list. Each time new articles arrive, the component rerenders to display the updated list, efficiently updating only the changed parts of the DOM while preserving the component’s state.
Remounting occurs when React unmounts the component and then mounts it again. This can happen due to changes in the component’s key prop, or when the component is conditionally rendered and its condition changes. Unlike rerendering, where the component updates in place, re-mounting involves tearing down the component's existing state and lifecycle methods and setting up a new instance. For example, imagine a user form that resets every time it is toggled on and off. When the form is hidden and then shown again, React unmounts the form component, losing its previous state and then remounts it as a new instance.
In the next lesson, we will learn about one of the powerful hooks in React, useEffect
which lets us perform specific actions during these phases in the component lifecycle.