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

Common Hook Typing Pitfalls

Avoid setState type mismatches, ref initialization errors, and dependency array type warnings.

Common Hook Typing Pitfalls

You'll learn: The most frequent TypeScript mistakes when working with React hooks and how to avoid them.

The Core Concept

Even experienced developers stumble over a few recurring TypeScript issues with hooks. These pitfalls typically involve mismatched types in setState, incorrectly initialized refs, and dependency array type warnings. Understanding these patterns helps you write cleaner, error-free code from the start.

setState Type Mismatches

The most common mistake is passing values that don't match your state type:

const [user, setUser] = useState<User | null>(null);

// ❌ Pitfall: passing wrong type
setUser({ name: 'Alice' }); // Error: missing required User properties

// ✅ Correct: match the full type
setUser({ id: 1, name: 'Alice', email: 'alice@example.com' });

Ref Initialization Errors

Forgetting null as the initial value for DOM refs causes instant errors:

// ❌ Pitfall: no initial value
const inputRef = useRef<HTMLInputElement>(); // Error!

// ✅ Correct: always initialize with null
const inputRef = useRef<HTMLInputElement>(null);

Dependency Array Type Warnings

TypeScript warns when dependency array types might change unexpectedly:

// ❌ Pitfall: object literal recreated each render
useEffect(() => {
  fetchData({ page: 1 }); // New object every time
}, [{ page: 1 }]); // Warning: unstable dependency

// ✅ Correct: use stable primitives
const page = 1;
useEffect(() => {
  fetchData({ page });
}, [page]);

Key Takeaway: The three most common hook typing errors are setState type mismatches (wrong shape), ref initialization without null, and dependency arrays with unstable reference types—catch these early and your TypeScript-React code becomes dramatically smoother.