The mounting phase is when a React component is created and added to the screen for the first time. It helps show content to users.
Mounting phase in React
Introduction
Syntax
React
useEffect(() => {
// code to run on mount
}, []);The empty array [] means this runs only once when the component appears.
This replaces older class methods like componentDidMount.
Examples
React
import React, { useEffect } from 'react'; function Welcome() { useEffect(() => { console.log('Component mounted'); }, []); return <h1>Hello!</h1>; }
React
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data));
}, []);Sample Program
This component shows seconds passed since it appeared. It starts a timer when mounted and cleans it up when removed.
React
import React, { useState, useEffect } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds(s => s + 1); }, 1000); return () => clearInterval(interval); // cleanup on unmount }, []); return <div>Seconds passed: {seconds}</div>; } export default Timer;
Important Notes
Always clean up timers or subscriptions in the return function inside useEffect to avoid bugs.
The mounting phase happens only once per component instance.
Summary
The mounting phase is when a component first appears on screen.
Use useEffect with an empty array [] to run code only once on mount.
This is useful for setup tasks like fetching data or starting timers.
Practice
1. What does the mounting phase in React mean?
easy
Solution
Step 1: Understand React component lifecycle phases
The mounting phase is the first phase when a component is created and inserted into the DOM.Step 2: Match the phase to the description
Mounting means the component appears on screen for the first time, not updates or removal.Final Answer:
When a component first appears on the screen -> Option BQuick Check:
Mounting phase = first appearance [OK]
Hint: Mounting means first time component shows [OK]
Common Mistakes:
- Confusing mounting with updating
- Thinking mounting means removal
- Mixing mounting with re-rendering
2. Which of the following is the correct way to run code only once when a React component mounts using hooks?
easy
Solution
Step 1: Recall useEffect dependency array usage
Passing an empty array [] runs the effect only once on mount.Step 2: Compare options
useEffect(() => { /* code */ }, []) uses [] so runs once; others run on every render or when dependencies change.Final Answer:
useEffect(() => { /* code */ }, []) -> Option AQuick Check:
Empty array means run once on mount [OK]
Hint: Empty array in useEffect runs once on mount [OK]
Common Mistakes:
- Omitting dependency array runs effect every render
- Using state or props array runs effect multiple times
- Confusing useEffect with useState
3. What will be logged to the console when this component mounts?
function Timer() {
React.useEffect(() => {
console.log('Timer started');
}, []);
return <div>Timer</div>;
}medium
Solution
Step 1: Analyze useEffect with empty dependency array
The effect runs once on mount, logging 'Timer started' once.Step 2: Confirm no repeated logs or errors
No dependencies means no repeated logs; no error occurs.Final Answer:
Timer started -> Option CQuick Check:
useEffect with [] logs once on mount [OK]
Hint: Empty array means effect runs once on mount [OK]
Common Mistakes:
- Thinking it logs every render
- Expecting no logs without return
- Assuming error due to missing dependencies
4. Identify the error in this React component related to the mounting phase:
function DataFetcher() {
React.useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
});
return <div>Loading...</div>;
}medium
Solution
Step 1: Check useEffect dependencies
Without a dependency array, useEffect runs after every render, causing repeated fetch calls.Step 2: Identify correct fix
Adding an empty array [] runs fetch only once on mount, preventing repeated calls.Final Answer:
Missing dependency array causes fetch on every render -> Option AQuick Check:
No [] means effect runs every render [OK]
Hint: Always add [] to run effect once on mount [OK]
Common Mistakes:
- Forgetting dependency array in useEffect
- Thinking fetch outside useEffect is needed
- Assuming useEffect cannot contain async calls
5. You want to fetch user data only once when a component mounts and store it in state. Which code correctly implements this mounting phase behavior?
function UserProfile() {
const [user, setUser] = React.useState(null);
// Which useEffect is correct?
A) React.useEffect(() => {
fetch('/user')
.then(res => res.json())
.then(data => setUser(data));
}, []);
B) React.useEffect(() => {
fetch('/user')
.then(res => res.json())
.then(data => setUser(data));
});
C) React.useEffect(() => {
fetch('/user')
.then(res => res.json())
.then(data => setUser(data));
}, [user]);
D) React.useEffect(() => {
fetch('/user')
.then(res => res.json())
.then(data => setUser(data));
}, [setUser]);
return user ? <div>{user.name}</div> : <div>Loading...</div>;
}hard
Solution
Step 1: Understand useEffect dependencies for fetching
Empty array [] runs effect once on mount; no dependencies cause repeated fetches.Step 2: Analyze each option
The useEffect with an empty dependency array fetches data only once on mount. Without any dependency array, the effect runs after every render. Depending onusercauses an infinite loop since updatingusertriggers re-renders. Depending onsetUserruns only once becausesetUseris stable, but it is unnecessary and may cause ESLint warnings.Final Answer:
useEffect with empty array to fetch once on mount -> Option DQuick Check:
Empty [] means fetch once on mount [OK]
Hint: Empty array in useEffect fetches once on mount [OK]
Common Mistakes:
- Leaving out dependency array causes infinite fetch
- Using state as dependency causing loops
- Misunderstanding stable functions as dependencies
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
