Component Mounting and Updating in React JS
Component Mounting and Updating are important concepts in React JS that explain how components enter the user interface and respond to changes in data. Understanding these concepts helps developers manage component behavior, update the UI efficiently, fetch data, and handle side effects correctly.
React JS Training: Explore JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Is the React Component Lifecycle?
The component lifecycle describes the different stages a React component goes through during its existence in an application. A component can be created, displayed, updated when its data changes, and eventually removed from the screen.
React components generally have three lifecycle stages:
- Mounting: The component is added to the user interface for the first time.
- Updating: The component renders again because its props, state, or relevant context have changed.
- Unmounting: The component is removed from the user interface.
Example
Imagine an online shopping application. When a product page first appears, the product component mounts. When the product price or quantity changes, the component updates. When the user navigates away and the component is removed, it unmounts.
2. What Is Component Mounting?
Component mounting is the process in which React creates a component's initial UI and adds it to the displayed application. For a function component, React executes the component function to calculate its initial output and commits the resulting UI.
Important Points About Mounting
- The component is added to the screen.
- Its initial props and state are used to calculate the UI.
- React commits the initial rendered output to the DOM.
- Effects may run after the initial commit to synchronize with external systems.
- Mounting logic is useful for tasks such as starting subscriptions or fetching initial data.
Example: A Simple Function Component
function Welcome() {
return (
<div>
<h1>Welcome to React JS</h1>
<p>This component has been mounted.</p>
</div>
);
}
export default Welcome;
When the application renders the Welcome component for the first time, React displays its heading and paragraph.
3. What Is Component Updating?
Component updating occurs when React renders a component again to reflect changed information. Common causes include a state update, new props from a parent, or a relevant context value changing.
Important Points About Updating
- React calculates the component's updated output.
- React compares the new output with the previous output and updates the DOM where necessary.
- State changes can cause a component to render again.
- New props can cause a child component to render again.
- Effects can re-run when their dependencies change.
Example: Updating State with useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase Count
</button>
</div>
);
}
export default Counter;
Explanation: Initially, the count is zero. When the user clicks the button, the state update requests another render. React then displays the updated count.
4. Mounting and Updating: Key Differences
| Basis |
Mounting |
Updating |
| Meaning |
Component appears for the first time. |
Component renders again to reflect changes. |
| Initial render |
Yes. |
No; the component has already mounted. |
| Common triggers |
Component is included in the rendered UI. |
State, props, or relevant context changes. |
| Function components |
Initial component render and commit. |
Subsequent render and commit when required. |
| useEffect behavior |
Runs after the initial commit when its dependencies permit. |
Runs again after a commit when dependencies change. |
| Class lifecycle method |
componentDidMount() |
componentDidUpdate() |
| Typical use |
Initial data loading and setting up subscriptions. |
Responding to changed inputs and synchronizing external systems. |
5. Component Mounting and Updating with useEffect
In modern React function components, the useEffect() Hook is commonly used to synchronize a component with external systems, such as APIs, timers, browser events, and subscriptions. Its behavior depends on the dependency array.
5.1 useEffect with an Empty Dependency Array
An empty dependency array means the Effect does not re-run because of ordinary changes to the component's props or state. It runs after the initial client-side commit. In development Strict Mode, React may perform an additional setup and cleanup cycle to help detect bugs.
import { useEffect } from "react";
function Welcome() {
useEffect(() => {
console.log("Component mounted");
}, []);
return <h1>Welcome to React</h1>;
}
export default Welcome;
Explanation: The Effect runs after the component's initial commit. It does not run again merely because the component renders due to a state change.
5.2 useEffect with Dependencies
When a dependency changes, React runs the previous cleanup function, if one exists, and then runs the Effect setup again after the updated commit.
import { useEffect, useState } from "react";
function UserProfile() {
const [userId, setUserId] = useState(1);
useEffect(() => {
console.log("Current user ID:", userId);
}, [userId]);
return (
<div>
<h2>User ID: {userId}</h2>
<button onClick={() => setUserId(userId + 1)}>
Next User
</button>
</div>
);
}
export default UserProfile;
Explanation: The Effect runs after the initial commit. Whenever the user clicks the button and the userId changes, React renders the updated UI and runs the Effect again.
5.3 useEffect Without a Dependency Array
If the dependency array is omitted, the Effect runs after every committed render. Use this pattern carefully because unnecessary work can affect performance, and state updates inside the Effect can cause repeated rendering.
import { useEffect, useState } from "react";
function RenderTracker() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect ran after a commit");
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Update Count
</button>
</div>
);
}
export default RenderTracker;
6. Component Mounting and Updating in Class Components
React class components provide lifecycle methods that run at particular points in a component's lifecycle. These methods remain useful when maintaining or understanding existing class-based applications.
6.1 componentDidMount()
The componentDidMount() method runs after a class component has been mounted. It is commonly used for initial data fetching, subscriptions, and other post-mount operations.
import { Component } from "react";
class Welcome extends Component {
componentDidMount() {
console.log("Component mounted");
}
render() {
return <h1>Welcome to React JS</h1>;
}
}
export default Welcome;
6.2 componentDidUpdate()
The componentDidUpdate() method runs after an update has been committed. It does not run for the initial mount. When performing an operation that depends on changed props or state, compare the current values with the previous values to avoid unnecessary repeated work.
import { Component } from "react";
class Counter extends Component {
state = { count: 0 };
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log("Count updated:", this.state.count);
}
}
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={() => this.setState(({ count }) => ({ count: count + 1 }))}>
Increase
</button>
</div>
);
}
}
export default Counter;
6.3 componentWillUnmount()
The componentWillUnmount() method runs immediately before a class component is removed. It is commonly used to clean up subscriptions, timers, and other resources established by the component.
import { Component } from "react";
class TimerMessage extends Component {
componentDidMount() {
this.timerId = setInterval(() => {
console.log("Timer is running");
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
console.log("Component removed and timer cleared");
}
render() {
return <p>Timer component is active.</p>;
}
}
export default TimerMessage;
7. The Role of Props in Component Updating
Props allow a parent component to pass data to a child component. When the parent supplies different props, React may render the child again to display the updated information.
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
function App() {
return (
<div>
<Greeting name="Amit" />
<Greeting name="Priya" />
</div>
);
}
export default App;
Explanation: The parent passes a different name prop to each instance of Greeting. Each child renders its own greeting. If the parent later passes a different name, the relevant child can display the new value.
8. The Role of State in Component Updating
State represents information that a component manages over time. When state is updated through a React state setter or a class component's setState(), React can render the component again to display the new value.
import { useState } from "react";
function ToggleMessage() {
const [visible, setVisible] = useState(false);
return (
<div>
<button onClick={() => setVisible(!visible)}>
Toggle Message
</button>
{visible && <p>Welcome to the React application!</p>}
</div>
);
}
export default ToggleMessage;
Explanation: When the button is clicked, the state changes. React updates the UI to show or hide the message.
9. Component Re-rendering and DOM Updating
Re-rendering means React executes a component's rendering logic again to calculate its output. A re-render does not necessarily mean that every DOM element is replaced. React compares the new result with the previous result and applies the necessary DOM changes.
How the Process Works
- A component is rendered for the first time or a relevant update is scheduled.
- React calculates the component's output.
- React determines the necessary changes.
- React commits the required DOM updates.
- Effects run according to their dependencies and lifecycle rules.
Important: A component may render again without a visible DOM change. Rendering and DOM mutation are related but different operations.
10. Common Mistakes During Mounting and Updating
- Updating state inside an Effect without a clear condition: This can create repeated renders or an infinite loop.
- Incorrect dependencies: Omitting reactive values used by an Effect can cause stale data or incorrect synchronization.
- Directly modifying state: Avoid mutating objects or arrays in state. Create new values and use the appropriate state setter.
- Performing side effects during rendering: Keep rendering logic pure. Perform external synchronization in Effects or event handlers.
- Forgetting cleanup: Clear timers, remove event listeners, and release subscriptions when they are no longer needed.
- Using outdated lifecycle methods: Avoid deprecated methods such as
componentWillMount() in new code.
- Assuming an Effect runs exactly once in development: Strict Mode can intentionally run an additional setup and cleanup cycle.
11. Best Practices for Component Mounting and Updating
- Use function components and Hooks for most new React development.
- Use
useEffect() when synchronizing with an external system, not for every calculation or state change.
- Specify all necessary reactive dependencies in an Effect.
- Return a cleanup function when a subscription, timer, or resource needs to be released.
- Keep rendering logic pure and avoid unnecessary state updates.
- Use stable, unique keys when rendering lists of components.
- Use class lifecycle methods appropriately when working with existing class components.
- Test mounting, updates, and unmounting to confirm that the UI and external resources behave correctly.
12. Practical Example: Tracking Component Mounting and Updating
The following example demonstrates an initial mount, state updates, and Effect cleanup in a function component.
import { useEffect, useState } from "react";
function LifecycleDemo() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Effect setup: count is", count);
return () => {
console.log("Effect cleanup for count", count);
};
}, [count]);
return (
<div>
<h1>Component Lifecycle Demo</h1>
<p>Current count: {count}</p>
<button onClick={() => setCount(previous => previous + 1)}>
Increase Count
</button>
</div>
);
}
export default LifecycleDemo;
Expected Behavior
- When the component first commits, the Effect setup runs with the initial count.
- When the button is clicked, React updates the state and renders the new count.
- After the updated commit, React runs the previous cleanup and then the new Effect setup.
- When the component is removed, React runs the final Effect cleanup.
Note: In development Strict Mode, React may run an extra setup and cleanup cycle. This helps developers verify that cleanup correctly reverses the Effect's setup.
13. Interview Questions and Answers
Q1. What is component mounting in React?
Mounting is the process in which a component is added to the rendered user interface for the first time.
Q2. What is component updating?
Updating occurs when React renders a component again to reflect changes in state, props, or relevant context.
Q3. What is componentDidMount()?
It is a class component lifecycle method that runs after the component mounts.
Q4. What is componentDidUpdate()?
It is a class component lifecycle method that runs after an update has been committed, but not after the initial mount.
Q5. How does useEffect() relate to mounting and updating?
The Effect setup runs after a commit when its dependency conditions are met. With an empty dependency array, it does not re-run because of ordinary prop or state changes. With dependencies, it re-runs when those dependencies change.
Q6. Why is cleanup important in React?
Cleanup prevents unwanted subscriptions, timers, and event listeners from continuing after they are no longer needed.
Q7. Does every re-render update the DOM?
No. React may render a component again without making any DOM changes if the resulting UI is unchanged.
Q8. What causes a component to update?
Common causes include state updates, new props, and changes to relevant context values.
14. Quick Revision Checklist
- Understand mounting, updating, and unmounting.
- Know how state and props can trigger rendering.
- Understand
useEffect() dependency arrays.
- Know the roles of
componentDidMount(), componentDidUpdate(), and componentWillUnmount().
- Understand Effect cleanup and React Strict Mode.
- Distinguish component re-rendering from actual DOM changes.
- Practice building a counter, toggle, or data-fetching component.
15. Conclusion
Component mounting and updating are fundamental concepts in React JS. Mounting introduces a component into the UI, while updating allows it to reflect changing data. Function components commonly use Hooks such as useState() and useEffect(), whereas class components provide lifecycle methods such as componentDidMount() and componentDidUpdate(). Understanding these concepts helps developers build responsive, efficient, and maintainable React applications.
Learn React JS with JustAcademy
Strengthen your understanding of React components, Hooks, state management, and application development through structured learning and practical exercises.
Explore JustAcademy React JS Training Course
Register for a React JS Course Demo