Course contentsShow
← React
Lesson 2384 of 2,39651. TypeScript with React BasicsFree lesson

Typing useEffect Dependencies

Ensure type safety in effect dependency arrays and avoid common TypeScript errors with callbacks.

Typing useEffect Dependencies

You'll learn how to ensure TypeScript catches errors in your useEffect dependency arrays and avoid common type mismatches with callbacks.

The Core Problem

TypeScript doesn't automatically validate that your useEffect dependencies match the values you're actually using inside the effect. However, when dependencies are typed correctly—especially when passing callbacks or complex objects—you can catch subtle bugs where stale closures or incorrect types slip through.

The main issues arise when:

  • Dependencies are inferred as broader types than needed
  • Callback functions in dependencies lack proper signatures
  • Async functions are used directly in useEffect

Typing Dependencies Correctly

// ✅ Good: Dependencies are clearly typed
const handleSearch = useCallback((query: string) => {
  console.log(query);
}, []);

useEffect(() => {
  handleSearch(searchTerm);
}, [handleSearch, searchTerm]); // TypeScript validates these match usage
// ❌ Problem: Async function returns Promise, not void
useEffect(async () => {
  await fetchData(); // TypeScript error!
}, []);

// ✅ Fixed: Define async function inside
useEffect(() => {
  const loadData = async () => {
    await fetchData();
  };
  loadData();
}, []);

Common Pitfalls

When a dependency is typed as any or lacks explicit types, TypeScript can't warn you about mismatches. Always ensure callback dependencies from useCallback have proper type signatures, and primitives in the dependency array match what you're actually using.

Key Takeaway: TypeScript validates useEffect dependencies against their usage inside the effect, but only if those dependencies have proper types—always type callbacks explicitly and avoid async functions as the effect itself.