Performance: Common lifecycle use cases
This affects how quickly components render and update, impacting interaction responsiveness and visual stability.
useEffect(() => { fetchData(); }, []);useEffect(() => { fetchData(); });| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Effect without dependencies | Multiple redundant updates | Multiple reflows | High paint cost | [X] Bad |
| Effect with empty dependency array | Single update | Single reflow | Low paint cost | [OK] Good |
| Effect with missing cleanup | Memory leaks increase DOM nodes | Potential reflows on event triggers | Medium paint cost | [!] Bad |
| Effect with proper cleanup | Stable DOM nodes | Minimal reflows | Low paint cost | [OK] Good |
useEffect hook in React functional components?useEffect hook runs side effects like data fetching or timers after rendering.useState, event handlers are functions, and styling is separate.[] means the effect runs once on mount only.function Timer() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <div>Count: {count}</div>;
}useEffect(() => {
const timer = setTimeout(() => {
console.log('Hello');
}, 1000);
});userId prop changes in a React component. Which useEffect hook is correct?function UserProfile({ userId }) {
const [user, setUser] = React.useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then(res => res.json())
.then(data => setUser(data));
}, ???);
return <div>{user ? user.name : 'Loading...'}</div>;
}userId changes to fetch new data.userId in the dependency array triggers effect on its change.Pass the test and this pattern moves unknown