Reading — step 1 of 5
Read
~1 min readHooks & State
useEffect Hook
Effects run AFTER render, for side effects (DOM, network, timers).
javascript
Dependencies array [id]: re-run effect when id changes.
Implementation:
python
Cleanup:
- Effect can return a cleanup function.
- Called before next effect or on unmount.
javascript
[] deps: run once on mount, cleanup on unmount.
[a, b] deps: re-run when a or b changes.
No deps array: run on every render. Almost never what you want.
Common patterns:
- Mount-only:
useEffect(() => {...}, []). Initialize, fetch, subscribe. - Reactive:
useEffect(() => {...}, [searchTerm]). Re-run on input change. - Cleanup-only: return cleanup; useful for subscriptions.
Pitfalls:
- Missing dependencies → stale closures.
- Too many dependencies → too many runs.
- Async effects: can race; debounce + cancel logic needed.
Modern alternatives:
- useSyncExternalStore: subscribe to external state.
- Suspense + use() (React 19): suspending data fetching.
- Server Components: no useEffect for data fetch; just await on server.
For our toy: simple effect queue; run after render commits.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…