Dependency Array

Last updated: 2026-11-02

Dependency Array Dependency Array

The dependency array tells an effect who it runs for: an empty array runs it once, and listing variables makes it re-run whenever any of them changes. The mental model is that the effect stays in sync with its dependencies — every reactive value read inside the effect should be listed there honestly. The array is not a performance knob you tune by hand; it is a declaration of what the effect depends on, and the linter can only check that declaration if you let it see every value.

GroupEffects & Performance
KindPattern

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

useEffect(fn)        // runs after every render
useEffect(fn, [])    // runs once after mount
useEffect(fn, [a])   // runs when a changes (compared with Object.is)

Returns:No return value; this entry describes an encoding pattern rather than a function.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

Clicking a different user shows "Loading…" first and then the matching name; even rapid clicks never mix the data up, because the old timer is cleaned up.

💡 Key Points

💡 Tip Dependencies are compared with Object.is: an object or function gets a fresh reference on every render, which means the dependency is effectively always changing.
⚠️ Warning Omitting a dependency on purpose buys you fewer runs at the price of a stale closure — think it through before you silence the exhaustive-deps lint warning.
ℹ️ Info The intuition that "[] runs once on mount" is often wrong: as soon as the effect uses a value that can change, that value belongs in the dependency array.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Why does an object in the dependency array always re-run the effect?
A Every render produces a new reference, so Object.is fails. Use useMemo to stabilize the reference, or store a primitive value as the dependency.
Q Why does [] run twice in development mode?
A StrictMode deliberately double-invokes effects to expose side effects that lack a cleanup; in production it runs only once.
Q How do I run logic when a certain prop changes?
A List it in the dependency array and write the logic inside the effect; when you need to skip the first run, use a ref to record whether the component has mounted.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏