All jobs / Frontend / web developer
Frontend / web developer interview question · 1–3 years
A setInterval inside useEffect always logs the initial count. Why?
The strongest answer
The effect's callback closed over the count from the render it was created in; either list count as a dependency and reset the interval, use a functional state update, or keep the latest value in a ref
Why it works
Right. Stale closure — the classic hooks trap.
What a good answer covers
- Closures capture the render's values.
- Dependencies re-create the effect.
- Functional updates avoid the capture.
- Refs hold the latest value.
Answers that fall short
- Close, but not the strongest: setInterval does not work in React
It works; the closure is the issue. - Weak: The count is a ref
It is state; the closure is old. - Red flag: The effect runs too often
It ran once and captured once.
Who gets asked this
More Frontend / web developer questions
- A member must not see 'Transfer ownership'. An admin must. What do you implement?
- When is useMemo worth it?
- Why wrap a handler in useCallback?
- The team argues whether a field is `userId` or `user_id`. What is OpenAPI for here?
- When does React.memo help, and when does it not?
- The register API can fail because the email is taken or because the password is too short. What should the UI…
- The app feels sluggish when typing in one field. How do you find the cause?
- Where should state live, as a rule?