useEffect hook
Watch the walkthrough
Open on InstagramQuick revision
useEffect synchronizes a component with an external system after a commit: a subscription, timer, browser API, or network request. Derive values from props and state while rendering when no external synchronization is needed.
Setup, dependencies, and cleanup
- Omitted dependency array: run after every commit.
- Empty array: no reactive dependencies; setup when mounted and cleanup when unmounted.
[userId]: rerun whenuserIdchanges, with cleanup of the previous setup first.- Include every reactive value read by the Effect. Do not remove dependencies to silence a linter.
- Cleanup removes listeners, clears timers, disconnects observers, or cancels/ignores obsolete requests.
Development Strict Mode can run an extra setup/cleanup cycle to expose missing cleanup. Make the synchronization safe to start and stop repeatedly. Effects do not run during server rendering.
Follow the repository example
Showing SubComponent mounts it. Changing userId cleans up the previous user and sets up the next one. Incrementing count does not rerun the [userId] Effect. Hiding the component runs cleanup and discards its local state.
Recall check
An Effect is not a generic place for every computation. Explain what external system it synchronizes with before adding one.
Reference: useEffect.