Performance: Mounting phase
This affects the initial page load speed and how quickly React components appear on screen.
import { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { setTimeout(() => { const result = heavyComputation(); setData(result); }, 0); }, []); if (data === null) return <div>Loading...</div>; return <div>{data}</div>; } function heavyComputation() { let sum = 0; for (let i = 0; i < 1e7; i++) sum += i; return sum; }
function MyComponent() { const data = heavyComputation(); return <div>{data}</div>; } function heavyComputation() { let sum = 0; for (let i = 0; i < 1e7; i++) sum += i; return sum; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous logic in render | 1 (initial mount) | 1 (initial layout) | High (delayed paint) | [X] Bad |
| Deferred heavy logic with useEffect | 1 (initial mount) | 1 (initial layout) | Low (fast paint) | [OK] Good |
function Timer() {
React.useEffect(() => {
console.log('Timer started');
}, []);
return <div>Timer</div>;
}function DataFetcher() {
React.useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
});
return <div>Loading...</div>;
}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>;
}user causes an infinite loop since updating user triggers re-renders. Depending on setUser runs only once because setUser is stable, but it is unnecessary and may cause ESLint warnings.Pass the test and this pattern moves unknown