TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation Β· 5.9K subscribers
Post #1390 316
πŸ› SPOT THE BUG #4
Language: JavaScript (React)

javascript
function UserProfile({ userId }) {
const [user, setUser] = useState(null);

useEffect(() => {
fetchUser(userId).then(data => setUser(data));
});

return <div>{user?.name}</div>;
}


What's the bug? πŸ‘‡

.
.
.

The bug: Missing dependency array in useEffect. Without [userId] (or even []), this effect runs after EVERY render - and since setUser triggers a re-render, and that re-render triggers the effect again, you get either an infinite fetch loop or, at minimum, wildly wasteful re-fetching.

Fixed version:
javascript
useEffect(() => {
fetchUser(userId).then(data => setUser(data));
}, [userId]); // only re-run when userId changes


⚠️ Bonus bug hiding here too: if userId changes quickly (user navigates between profiles fast), an OLDER fetch can resolve AFTER a newer one, overwriting fresh data with stale data ("race condition"). The fix is usually a cleanup function that ignores outdated responses:

javascript
useEffect(() => {
let ignore = false;
fetchUser(userId).then(data => {
if (!ignore) setUser(data);
});
return () => { ignore = true; };
}, [userId]);


React hooks bugs are EXTREMELY common in frontend interviews right now. Have you been bitten by a missing dependency array before? πŸ‘‡
  • ❀ 1
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026πŸ’Ό Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026πŸ’Ό What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’