Course contentsShow
← React
Lesson 1030 of 2,39626. Rules of Hooks Deep DiveFree lesson

Calling Hooks in useEffect Callbacks

Why placing a hook call inside the useEffect callback function breaks the rules.

Calling Hooks in useEffect Callbacks

You'll learn why you cannot call hooks inside the callback function you pass to useEffect, even though it might seem logical for certain use cases.

The Problem

You might be tempted to call a hook inside your useEffect callback, thinking it would help manage side-effect-related state or logic. This violates the Rules of Hooks and will break your application.

// ❌ WRONG - Hook inside useEffect callback
function BadComponent() {
  useEffect(() => {
    const [data, setData] = useState(null); // ILLEGAL!
    // ... fetch logic
  }, []);
}

Why This Breaks Everything

Remember that hooks must be called in the same order on every render. The useEffect callback doesn't run during render—it runs after render completes. This means:

  1. On the first render, useState inside the effect doesn't get called yet
  2. React builds its hook registry without that useState
  3. When the effect runs later, React tries to register a new hook
  4. On re-renders, the hook indices are now misaligned

It's like showing up to a numbered seating arrangement after everyone else has already sat down—your seat number doesn't match React's expectations.

The Right Approach

Declare all hooks at the top level, then use their results inside your effect:

// ✅ CORRECT - Hook at top level
function GoodComponent() {
  const [data, setData] = useState(null);
  
  useEffect(() => {
    // Use setData here, but don't declare hooks
    fetchData().then(setData);
  }, []);
}

Key Takeaway: Hooks must always be called at the component's top level during render—never inside useEffect callbacks, event handlers, or any other nested function that doesn't run during the render phase.