Component Mounting and Updating in React JS – Complete Notes
Component Mounting and Updating are important stages in the React component lifecycle. Mounting occurs when a component is added to the screen for the first time, while updating occurs when a component receives new props or state and React needs to render it again. Understanding these stages helps developers manage component rendering, API requests, side effects, and UI updates effectively.
In modern React, function components commonly use Hooks such as useState and useEffect to manage state and synchronize with external systems. Class components use lifecycle methods such as componentDidMount() and componentDidUpdate().
Official Documentation: React Component and Lifecycle Methods
1. What Is the React Component Lifecycle?
The React component lifecycle describes the stages a component goes through during its existence in an application.
A component generally passes through three main stages:
- Mounting: The component is created and added to the screen.
- Updating: The component renders again because its props, state, or relevant context have changed.
- Unmounting: The component is removed from the screen.
Simple Lifecycle Diagram
Component Created
|
v
MOUNTING
|
v
Component Appears on Screen
|
v
UPDATING
|
v
Props or State Change
|
v
Component Renders Again
|
v
UNMOUNTING
|
v
Component Removed from Screen
A component can update many times during its lifetime. It does not have to update before it is unmounted.
2. What Is Component Mounting?
Mounting is the stage when React creates a component's initial UI and adds it to the screen. During mounting, React renders the component and commits the resulting changes to the DOM.
What Happens During Mounting?
- The component receives its initial props.
- Its initial state is established.
- React renders the component's JSX.
- React commits the required DOM changes.
- Effects may run after the component commits.
Example: Function Component Mounting
function Welcome() {
return (
<div>
<h1>Welcome to React JS</h1>
<p>This component is mounted on the screen.</p>
</div>
);
}
export default Welcome;
Explanation
When React first renders the Welcome component and commits it to the DOM, the component is mounted. Its heading and paragraph become part of the visible page.
3. What Is Component Updating?
Updating occurs when React renders a component again because relevant inputs have changed. These inputs can include props, state, or context.
Common Reasons for Updating
- A state setter such as
setCount() updates state.
- A parent component passes new props.
- A context value used by the component changes.
- A parent re-renders and React renders the child again.
A parent re-render does not necessarily mean the child's displayed output will change. React may render a child again even if its props are unchanged, unless an applicable optimization allows it to skip rendering.
Example: Component Updating with useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation
- The component initially renders with
count equal to zero.
- The user clicks the Increase button.
setCount() requests a state update.
- React renders the component again with the new count.
- React commits any necessary changes to the DOM.
4. Mounting and Updating in Function Components
Function components use Hooks to manage state and synchronize with external systems. The useEffect Hook is commonly used when an operation needs to run after a component commits or when specific dependencies change.
Example: Detecting Initial Mount and Updates
import { useEffect, useState } from "react";
function Profile() {
const [name, setName] = useState("Alex");
useEffect(() => {
console.log("Profile Effect ran");
return () => {
console.log("Profile Effect cleanup");
};
}, [name]);
return (
<div>
<h2>Name: {name}</h2>
<button onClick={() => setName("Sam")}>
Update Name
</button>
</div>
);
}
export default Profile;
Explanation
- The component initially renders with the name Alex.
- After the initial commit, the Effect runs.
- When the name changes to Sam, React renders the component again.
- React runs the previous Effect cleanup before running the updated Effect.
Important: This Effect depends on name. It runs after the initial commit and again when that dependency changes. The Effect is not a general-purpose callback for every component lifecycle event.
5. Understanding useEffect During Mounting and Updating
The useEffect Hook synchronizes a component with an external system. Its dependencies determine when React needs to run the Effect again.
Example 1: Effect Without a Dependency Array
useEffect(() => {
console.log("Effect ran after a commit");
});
This Effect runs after every commit of the component, including commits caused by state or prop updates.
Example 2: Effect with an Empty Dependency Array
useEffect(() => {
console.log("Effect setup");
}, []);
This Effect runs after the initial commit. In development, React Strict Mode may perform an additional setup and cleanup cycle to help detect bugs.
Example 3: Effect with Dependencies
useEffect(() => {
console.log("Name changed:", name);
}, [name]);
This Effect runs after the initial commit and again when the value of name changes.
| Effect Syntax |
When It Runs |
| No dependency array |
After every commit. |
Empty array [] |
After the initial commit; Strict Mode can add a development-only setup and cleanup cycle. |
[value] |
After the initial commit and when value changes. |
Effects run only on the client. Include all reactive values used by an Effect in its dependency array.
6. Component Mounting in Class Components
Class components provide lifecycle methods for handling mounting, updating, and unmounting.
Important Mounting Methods
| Method |
Purpose |
constructor() |
Initializes state and binds methods when needed. |
render() |
Returns the UI that React should display. |
componentDidMount() |
Runs after the component has mounted and its initial DOM has been committed. |
Example: componentDidMount()
import { Component } from "react";
class Welcome extends Component {
componentDidMount() {
console.log("Welcome component mounted");
}
render() {
return <h1>Welcome to React JS</h1>;
}
}
export default Welcome;
Explanation
- React creates the class component.
- The
render() method describes the UI.
- React commits the UI to the DOM.
componentDidMount() runs after the component mounts.
Common Uses of componentDidMount()
- Starting subscriptions.
- Fetching initial data when appropriate.
- Initializing certain third-party libraries.
- Interacting with DOM nodes after they have been committed.
Any resource established in componentDidMount() may need to be released in componentWillUnmount().
7. Component Updating in Class Components
When a class component receives new props or state, React may render it again. The componentDidUpdate() lifecycle method runs after an update has been committed, but it does not run for the initial mount.
Important Updating Methods
| Method |
Purpose |
render() |
Calculates the UI for the current props and state. |
shouldComponentUpdate() |
Can help decide whether React should skip a class component's re-render. |
componentDidUpdate() |
Runs after an update has been committed. |
Example: componentDidUpdate()
import { Component } from "react";
class Counter extends Component {
state = {
count: 0
};
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log("Count changed:", this.state.count);
}
}
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button
onClick={() =>
this.setState(state => ({
count: state.count + 1
}))
}
>
Increase
</button>
</div>
);
}
}
export default Counter;
Explanation
- The initial state sets the count to zero.
- Clicking the button requests a state update.
- React renders the component with the new state.
componentDidUpdate() runs after the update is committed.
- The comparison with
prevState.count ensures the log occurs only when the count has changed.
Important: If you call setState() inside componentDidUpdate(), guard the update with a suitable condition. Otherwise, you may create a repeated update loop.
8. Mounting vs Updating
| Feature |
Mounting |
Updating |
| Meaning |
Component is added to the screen. |
Component is rendered again because its inputs or relevant context have changed. |
| Frequency |
Occurs when that component instance is mounted. |
Can occur many times during the component's lifetime. |
| Initial state |
Initial state is established. |
Existing state is updated or preserved as appropriate. |
| Function component behavior |
Initial render and commit. |
Subsequent renders and commits. |
| Class lifecycle method |
componentDidMount() |
componentDidUpdate() |
| Effect behavior |
Effects can run after the initial commit. |
Effects may rerun when their dependencies change. |
| DOM behavior |
React adds the required DOM nodes. |
React updates the DOM as needed. |
9. Example: Updating a Component Through Props
Props allow a parent component to pass information to a child component. When the parent supplies a new prop value, React can render the child again.
Child Component
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
export default Greeting;
Parent Component
import { useState } from "react";
import Greeting from "./Greeting";
function App() {
const [name, setName] = useState("Alex");
return (
<div>
<Greeting name={name} />
<button onClick={() => setName("Sam")}>
Change Name
</button>
</div>
);
}
export default App;
Explanation
- The parent initially passes
name="Alex".
- The child displays “Hello, Alex!”.
- The button changes the parent's state to Sam.
- The parent renders again and passes the updated prop.
- The child can render with the new name.
10. Understanding Re-rendering
A re-render means React calls a component's rendering logic again to calculate its next UI. A re-render does not always mean that React changes the actual DOM.
Common Causes of Re-rendering
- A component's state is updated.
- A parent component renders and renders its child again.
- A context value used by the component changes.
- A subscribed external store reports a change through its React integration.
Example
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
console.log("App rendered");
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase
</button>
</div>
);
}
export default App;
When the count changes, React renders the component again. The console message demonstrates the rendering behavior during development. Development tools such as Strict Mode can cause additional render calls, so console logs should not be treated as a precise lifecycle counter.
11. Cleaning Up During Unmounting
Although mounting and updating are the main topics, unmounting is important because a component may need to release resources before it is removed from the screen.
Function Component Cleanup
import { useEffect } from "react";
function TimerComponent() {
useEffect(() => {
const timerId = setInterval(() => {
console.log("Timer running");
}, 1000);
return () => {
clearInterval(timerId);
};
}, []);
return <h2>Timer Component</h2>;
}
export default TimerComponent;
Class Component Cleanup
import { Component } from "react";
class TimerComponent extends Component {
componentDidMount() {
this.timerId = setInterval(() => {
console.log("Timer running");
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return <h2>Timer Component</h2>;
}
}
export default TimerComponent;
Both examples start an interval when the component mounts and clear it when the component is removed. The cleanup prevents the timer from continuing unnecessarily.
12. Common Mistakes During Mounting and Updating
Mistake 1: Assuming useEffect Always Runs Only Once
An Effect with an empty dependency array runs after the initial commit, but Strict Mode may perform an extra development-only setup and cleanup cycle. Effects should be safe to set up and clean up correctly.
Mistake 2: Forgetting Effect Dependencies
Leaving out a reactive value can cause an Effect to use outdated information. Include the reactive values it reads.
Mistake 3: Updating State Without a Condition in componentDidUpdate()
Calling setState() unconditionally inside componentDidUpdate() can cause repeated updates. Compare current and previous props or state before requesting another update.
Mistake 4: Performing Side Effects During Rendering
Do not start subscriptions, set timers, or mutate external systems during the render calculation. Use an appropriate Effect or event handler.
Mistake 5: Confusing Re-rendering with DOM Updates
React may render a component again but commit no DOM changes if the resulting output is unchanged.
Mistake 6: Forgetting Cleanup
Listeners, timers, and connections may continue running if they are not released when they are no longer needed.
13. Best Practices
- Keep component rendering pure.
- Use state and props to describe the UI.
- Use
useEffect to synchronize with external systems.
- Declare all necessary Effect dependencies.
- Clean up subscriptions, intervals, and listeners.
- In class components, compare previous props and state before triggering additional updates inside
componentDidUpdate().
- Avoid unnecessary state variables for values that can be calculated during rendering.
- Use React DevTools to inspect component rendering and performance.
- Remember that rendering does not always mean a DOM mutation.
- Prefer function components and Hooks for new React code unless a class component is needed for a specific reason.
14. Interview Questions and Answers
Q1. What is component mounting in React?
Answer: Mounting is the stage when React adds a component to the screen for the first time.
Q2. What is component updating?
Answer: Updating occurs when React renders a component again because its props, state, or relevant context have changed.
Q3. What is componentDidMount()?
Answer: It is a class component lifecycle method that runs after the component has mounted and its initial DOM has been committed.
Q4. What is componentDidUpdate()?
Answer: It is a class component lifecycle method that runs after an update has been committed. It does not run for the initial mount.
Q5. How are mounting and updating handled in function components?
Answer: Function components render based on props and state. Hooks such as useState manage state, while useEffect synchronizes the component with external systems.
Q6. What causes a component to re-render?
Answer: Common causes include state updates, parent rendering, and changes to context values used by the component.
Q7. Does every re-render update the DOM?
Answer: No. React calculates the next UI and commits DOM changes only when needed.
Q8. What is the purpose of an Effect cleanup function?
Answer: It releases resources created by an Effect, such as timers, event listeners, and external connections.
Q9. Why should state updates in componentDidUpdate() be conditional?
Answer: An unguarded state update can cause a repeated update loop. Comparing previous and current values helps prevent unnecessary updates.
Q10. What is the difference between mounting and unmounting?
Answer: Mounting adds a component to the screen, whereas unmounting removes it and provides an opportunity to clean up resources.
15. Practice Exercises
- Create a function component that displays a welcome message when mounted.
- Create a counter that updates when a button is clicked.
- Use
useEffect to update the browser tab title when a counter changes.
- Create a parent component that passes a name to a child through props.
- Build a class component that logs a message in
componentDidMount().
- Build a class component that logs state changes in
componentDidUpdate().
- Create a timer that starts on mounting and stops during cleanup.
- Explain why a re-render does not necessarily mean the DOM has changed.
- Test an Effect under Strict Mode and observe its setup and cleanup behavior.
- Compare class lifecycle methods with function component Hooks.
16. Quick Revision Checklist
- Mounting means adding a component to the screen.
- Updating means rendering a component again when relevant inputs change.
- Unmounting means removing a component from the screen.
componentDidMount() runs after a class component mounts.
componentDidUpdate() runs after an update, not after the initial mount.
useEffect synchronizes function components with external systems.
- Effect dependencies determine when an Effect needs to run again.
- Cleanup releases resources when synchronization changes or ends.
- Re-rendering does not necessarily change the DOM.
- Use conditional logic before requesting additional state updates in
componentDidUpdate().
17. React JS Training Resources
Explore these resources to learn React component lifecycle concepts, Hooks, and modern React application development.
18. Conclusion
Component mounting and updating are fundamental concepts in React. Mounting happens when a component is added to the screen, while updating occurs when React renders it again because relevant props, state, or context values change. Class components provide lifecycle methods such as componentDidMount() and componentDidUpdate(), while function components use Hooks such as useState and useEffect. Understanding these concepts helps developers manage UI updates, external synchronization, and cleanup more reliably.