Summary of "useEffect Explained Dependency Array, Cleanup & Async"
Main Ideas, Concepts, and Lessons
-
React component responsibility
- A React component’s core job is to take data (inputs/props/state) and return UI.
- When treated like a pure function, the same inputs produce the same output.
-
What “side effects” are (and why they matter)
- Real apps need work beyond rendering, such as:
- fetching data from an API
- updating browser/UI outside React’s render
- opening real-time connections (e.g., sockets)
- starting/stopping timers
- subscribing/unsubscribing to events
- A side effect = any operation that interacts with the outside world and not just rendering.
- React may render a component multiple times, so side effects must be placed carefully to avoid repeated unintended execution.
- Real apps need work beyond rendering, such as:
-
What
useEffectdoesuseEffectprovides a safe, controlled place to run side effects after render.- It is commonly used for:
- data fetching
- timers
- event listeners
- subscriptions / sockets
Methodology / Structure of useEffect (with Detailed Bullet Points)
1) Basic Syntax and Purpose
useEffecthas two key parts:- A function: the side-effect logic to run
- A dependency array: determines when the effect runs
- This array is the developer’s way of telling React which values the effect depends on.
2) Dependency Array Behaviors (3 Main Versions)
-
No dependency array
- Runs after every render
- Typically a beginner mistake
-
Empty dependency array (
[])- Runs exactly once when the component mounts
- Useful for:
- fetching initial data
- setting up connections
- reading local storage
-
Dependency array with values (
[someValue])- Runs when the component mounts and again whenever those values change
- Example concept:
- fetch user profile whenever
userIdchanges
- fetch user profile whenever
3) Cleanup Functions (“Automatic Off Switch”)
- Some effects start something that must be stopped, such as:
- intervals/timers
- event listeners
- subscriptions
- web socket connections
- Rule/Fix
- If your effect starts something, your effect should return a cleanup to stop it.
- When cleanup runs
- When the component unmounts
- And right before the effect runs again due to dependency changes
4) Dependency Correctness (Avoid Stale Data)
- If an effect reads a value from the component scope, that value should go into the dependency array.
- Otherwise, the effect may use stale values captured from when it first ran (stale closure).
- The video also advises:
- Use the ESLint React hooks plugin warnings
- They exist to catch missing dependencies.
The Five Mistakes to Avoid (Detailed)
-
Missing dependencies → stale closure / outdated data
- Problem pattern:
- effect uses
countbutcountis not in the dependency array - effect runs once (e.g.,
[]), capturescount = 0 - later UI updates
countto 5, but effect still “thinks” it’s 0
- effect uses
- Fix:
- include every value the effect reads in the dependency array
- Problem pattern:
-
Infinite loops from wrong dependency choices
- Problem pattern A (self-triggering state update)
- effect fetches users, then calls
setUsers(...) - but
usersis also in the dependency array - setUsers triggers re-render → effect runs again → fetch/set repeats forever
- effect fetches users, then calls
- Fix:
- If you want fetch only once: use
[] - If you want reruns on some input change: depend on the input (e.g.,
query), not the state you set (e.g.,users)
- If you want fetch only once: use
- Problem pattern A (self-triggering state update)
-
Objects/functions in the dependency array break reference equality
- Problem pattern:
- you include
options(an object) in dependencies - even if the object content looks identical, it’s a new reference each render
- React thinks it changed → effect reruns → state updates → rerender → new reference → infinite loop
- you include
- Also applies to functions defined inside the component.
- Fix options:
- Fix 1: move the object/function outside the component (module scope) so it stays stable
- Fix 2: move creation inside the effect so it’s not listed as a dependency
- Mental model:
- anything created inside the component body is recreated on every render
- Problem pattern:
-
Marking the effect itself as
async- Problem:
useEffect(async () => ...)makes the effect return a Promise- React expects the cleanup to be a function or nothing, so cleanup won’t work correctly
- Fix:
- keep the
useEffectfunction non-async - define an inner async function and call it immediately
- keep the
- Problem:
-
Race conditions in async work (e.g., search)
- Problem:
- user types quickly; multiple fetches occur
- responses can return out of order
- older responses may overwrite newer results
- Fix shown:
- use a cancellation flag in cleanup
- set
isCanceled = falsewhen the effect starts - when the cleanup runs, set
isCanceled = true - only call
setResults(...)ifisCanceledis stillfalse
- set
- effect dependency change triggers the previous cleanup, preventing stale updates
- use a cancellation flag in cleanup
- Problem:
Overuse / Incorrect Use of useEffect (Derived Values Instead)
When useEffect isn’t necessary
- If a value can be computed from existing state/props, don’t sync it with
useEffect. - Example:
- keeping
fullNamein sync withfirstName+lastName - better approach: compute
fullNameduring render - benefits:
- no extra state
- no extra effect
- fewer re-renders
- keeping
Resetting forms when props change (key)
- Example concept:
- resetting a form when a prop changes using
useEffectis overcomplicated
- resetting a form when a prop changes using
- Better approach:
- use React’s
keyprop - when
keychanges, React unmounts/remounts the component, resetting state automatically
- use React’s
- Key question before writing
useEffect:- “Can this be computed during render?”
- “Can a
keyprop solve it?”
Consolidated “Bring It All Together” Takeaway
useEffectis for side effects outside React, such as fetching data, timers, subscriptions, etc.- The dependency array controls timing:
[]→ once on mount[values...]→ when those values change- no array → after every render
- Use cleanup to stop anything your effect starts.
- Avoid the five mistakes:
- missing dependencies (stale closures)
- infinite loops (wrong dependencies, especially state you set)
- objects/functions in dependencies (reference inequality)
- writing the effect function as
async - race conditions (need cancellation logic)
- Don’t overuse
useEffectfor derived values—compute them directly or usekeyfor resets.
Speakers / Sources Featured
- Speaker: The video narrator/author (not identified by name in the subtitles).
- Source libraries/frameworks mentioned: React (including hooks like
useEffect, and thekeyprop), JavaScript (closures, reference equality), ESLint React hooks plugin.
Category
Educational
Share this summary
Is the summary off?
If you think the summary is inaccurate, you can reprocess it with the latest model.
Preparing reprocess...