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

Calling Hooks in Regular Functions

Why hooks can only be called in components or custom hooks, not helper functions.

Calling Hooks in Regular Functions

You'll learn why hooks can only be called from React components or custom hooks, not from regular helper functions.

The Core Restriction

Hooks rely on React's internal tracking system that's tied to component render cycles. When you call a hook, React associates it with the currently rendering component or custom hook. Regular JavaScript functions don't participate in React's rendering system, so they have no "slot" in React's hook registry.

// ❌ WRONG: Hook in a regular helper function
function calculateTotal(items) {
  const [tax, setTax] = useState(0); // ERROR!
  return items.reduce((sum, item) => sum + item.price, 0) + tax;
}

function CheckoutComponent() {
  const items = [{ price: 10 }, { price: 20 }];
  const total = calculateTotal(items); // This breaks everything
  return <div>Total: {total}</div>;
}

Why This Rule Exists

React tracks hooks by call order within a component or custom hook. When you call a helper function like calculateTotal(), React doesn't know it's supposed to track hooks there — it's just a regular JavaScript function call from React's perspective. The hook won't be properly registered, and React's internal state will become corrupted.

The Correct Pattern

If your helper function needs hooks, it must be a custom hook (starting with use):

// ✅ CORRECT: Custom hook
function useCalculateTotal(items) {
  const [tax, setTax] = useState(0);
  return { total: items.reduce((sum, item) => sum + item.price, 0) + tax, setTax };
}

function CheckoutComponent() {
  const items = [{ price: 10 }, { price: 20 }];
  const { total, setTax } = useCalculateTotal(items);
  return <div>Total: {total}</div>;
}

Key Takeaway: Hooks can only be called from React components or custom hooks (functions starting with use), never from regular helper functions, because React's hook tracking system only operates within the React rendering context.