useState and useEffect
Give a real production-style example of using useState and useEffect. Walk through the scenario end-to-end.
Answers use simple, clear English.
Quick interview answer
Scenario: Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup. Implementation notes: Exhaustive deps or eslint-plugin-react-hooks; prefer useQuery/RSC for data fetch.
Detailed answer
Scenario: Fetch user profile on mount: useEffect with [userId] deps; abort fetch in cleanup. Implementation notes: Exhaustive deps or eslint-plugin-react-hooks; prefer useQuery/RSC for data fetch. 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: Tech Lead.
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?