DEV Community

Cover image for 5 React interview questions I'd actually ask (and how I'd answer them)
Tarun Sharma
Tarun Sharma

Posted on

5 React interview questions I'd actually ask (and how I'd answer them)

Most "React interview questions" lists online are either trivia (define useEffect) or so advanced they're not useful below 3-4 years of experience. Here are 5 I think are actually worth knowing, with the answer I'd give if asked.

1. What does this log, and why?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
Enter fullscreen mode Exit fullscreen mode

It logs 3, 3, 3. var gives the whole loop one shared variable, so by the time the callbacks run, the loop has already finished and i is 3. Swap var for let and it logs 0, 1, 2, let creates a fresh binding for every iteration, so each callback closes over its own copy.

2. Why doesn't an empty dependency array guarantee no stale-closure bugs?

An effect with [] only runs once, but any function or state it references from the render it was created in is frozen at that value forever, that's a stale closure. It's the same mechanism as question 1, just applied to a React render instead of a loop iteration.

3. What's the actual difference between useMemo and useCallback?

useCallback(fn, deps) is just useMemo(() => fn, deps). One memoizes a value, the other memoizes a function reference. People treat them as separate concepts when one is a special case of the other.

4. Why can a sibling component re-render even though its own props didn't change?

Because React re-renders every child of a component that re-renders, by default, regardless of whether that specific child's props changed. React.memo is what actually stops it, re-rendering isn't opt-out at the parent level, it's opt-in per child.

5. What does the virtual DOM actually skip?

It skips DOM writes, not DOM reads or re-renders. React still runs your component function and builds a new tree every render; the virtual DOM diff is what decides which actual DOM mutations are necessary, which are usually the expensive part.

What would you add to this list?

Top comments (0)