useState and useEffect
Design a small subsystem that relies on useState and useEffect. Outline components, data flow, failure modes, and metrics.
Answers use simple, clear English.
Quick interview answer
Use useState and useEffect as the core idea. Example shape: Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup..
Detailed answer
Use useState and useEffect as the core idea. Example shape: Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup.. Watch for: Missing deps cause stale bugs; effect for derived state often wrong — compute inline.. Measure success via latency/error/saturation. 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?