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

Dynamic Hook Calls Based on Props

Why conditionally calling hooks based on prop values breaks React's hook tracking.

Dynamic Hook Calls Based on Props

What you'll learn: Why you can't conditionally call hooks based on incoming prop values—even though it seems perfectly reasonable.

The Tempting Pattern

When you receive props, it's natural to think "if this prop is true, I need this hook; otherwise, I don't." This seems logical in normal programming, but it violates React's core hook invariant: hooks must be called in the same order every render.

Why Props Make It Tricky

Props can change between renders. When you write:

function MyComponent({ needsAnimation }) {
  if (needsAnimation) {
    const position = useSpring(); // ❌ Conditional hook call!
  }
  
  const [count, setCount] = useState(0);
}

React expects the same number of hooks in the same order every time this component renders. When needsAnimation toggles from true to false, suddenly useSpring disappears—React's internal hook index now points useState to where useSpring used to be. Everything breaks.

The Problem in Motion

First render (needsAnimation = true):

  • Hook #1: useSpring
  • Hook #2: useState

Second render (needsAnimation = false):

  • Hook #1: useState ← React thinks this is still useSpring!

React's hook registry is now completely misaligned, causing cryptic errors or wrong values.

The Solution Pattern

Always call the hook, then conditionally use its result:

function MyComponent({ needsAnimation }) {
  const position = useSpring(); // ✅ Always called
  const [count, setCount] = useState(0);
  
  // Conditionally USE the result
  const style = needsAnimation ? { transform: position } : {};
}

Key Takeaway: Props change, but your hook call structure must remain constant—call hooks unconditionally at the top level, then branch on their results.