useState and useEffect
As a Senior engineer, explain useState and useEffect. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Senior depth: start with the problem, then mechanism, then a short example. useState triggers re-render on update — functional updater avoids stale closures.
Detailed answer
At Senior depth: start with the problem, then mechanism, then a short example. useState triggers re-render on update — functional updater avoids stale closures. useEffect runs after paint; cleanup on unmount/deps change. Deps array controls re-run. Core: useState triggers re-render on update — functional updater avoids stale closures. useEffect runs after paint; cleanup on unmount/deps change. Deps array controls re-run. Real-time example: Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup. Pros: Core hooks model side effects declaratively. Cons: Missing deps cause stale bugs; effect for derived state often wrong — compute inline. Common mistakes: Empty deps with props/state inside; no cleanup on subscriptions/timers. Best practices: Exhaustive deps or eslint-plugin-react-hooks; prefer useQuery/RSC for data fetch. Audience level: Senior.
Full explanation
useState triggers re-render on update — functional updater avoids stale closures. useEffect runs after paint; cleanup on unmount/deps change. Deps array controls re-run.
Real example & use case
Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup.
Pros & cons
Pros: Core hooks model side effects declaratively. Cons: Missing deps cause stale bugs; effect for derived state often wrong — compute inline.
Common mistakes
Empty deps with props/state inside; no cleanup on subscriptions/timers.
Best practices
Exhaustive deps or eslint-plugin-react-hooks; prefer useQuery/RSC for data fetch.
Follow-up questions
- How would you test useState and useEffect?
- What metrics prove useState and useEffect is healthy in prod?
- How does useState and useEffect change at 10× traffic?