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:
- On the first render,
useStateinside the effect doesn't get called yet - React builds its hook registry without that
useState - When the effect runs later, React tries to register a new hook
- 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.