Course contentsShow
← TypeScript
Lesson 1522 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Typing useEffect Dependencies

Ensure exhaustive dependency arrays with proper types to avoid stale closure issues.

Typing useEffect Dependencies

You'll learn: How to properly type useEffect dependency arrays to catch stale closure bugs at compile time.


The Core Problem

When you use useEffect, React expects you to list every variable from outside the effect that you reference inside it. If you forget something, you get a stale closure — your effect captures an old value and never sees updates.

TypeScript can't automatically verify your dependency array is complete. But with the right patterns, you can use types to enforce exhaustiveness and catch mistakes before they cause bugs.


The Basic Pattern

The rule is simple: every value your effect reads must be in the dependency array.

If your effect uses count, user.id, or fetchData, all of those must appear in [count, user.id, fetchData].

TypeScript won't stop you from writing [], but with eslint-plugin-react-hooks and proper typing of your dependencies, you get warnings when dependencies change type or when you reference unstable values.


Type-Safe Dependency Strategy

Type your dependencies explicitly when they're complex:

  • If you pass a callback into the array, type it with useCallback so its signature is stable
  • If you reference object properties, destructure them outside the effect so TypeScript tracks individual primitives
  • If you have conditional dependencies, use union types to make all branches explicit

Avoid generic any or unknown in dependency arrays — these hide type changes that would invalidate your effect.


Analogy

Think of the dependency array as a security checkpoint manifest. You list everything you're bringing in. If the types of those items change (a string becomes number, a function signature shifts), TypeScript and your linter will flag the mismatch — preventing you from smuggling outdated values into your effect.


Key Takeaway: Use explicit types for useEffect dependencies, avoid any, and combine TypeScript with ESLint rules to enforce exhaustive dependency arrays and eliminate stale closure errors.