Course contentsShow
← React
Lesson 975 of 2,39625. Custom HooksFree lesson

Only React Functions Can Call Hooks

Hooks work in function components and custom hooks only—regular utility functions cannot use them.

Only React Functions Can Call Hooks

What you'll learn: Where hooks are allowed to run and why regular JavaScript functions can't use them.


Hooks have a restricted "calling environment"—they only work inside React function components and custom hooks. You cannot call hooks from regular utility functions, class methods, event handlers, or anywhere outside these two contexts.

The Two Valid Places for Hooks

1. React Function Components

function MyComponent() {
  const [count, setCount] = useState(0); // ✅ Valid
  return <div>{count}</div>;
}

2. Custom Hooks

function useCounter() {
  const [count, setCount] = useState(0); // ✅ Valid
  return [count, setCount];
}

Invalid Hook Usage

// ❌ Regular utility function
function formatData(data) {
  const [formatted, setFormatted] = useState(data); // ERROR!
  return formatted;
}

// ❌ Event handler
function handleClick() {
  const value = useState(0); // ERROR!
}

// ❌ Class method
class MyClass {
  doSomething() {
    useEffect(() => {}); // ERROR!
  }
}

Why This Rule Exists

React tracks hooks by their call order within a specific component instance. React components and custom hooks create that tracking context. Regular functions don't have this context, so React can't maintain the internal state structure hooks depend on.

Think of it like a library card system: hooks need a "library card" (component identity) to check out resources (state, effects). Regular functions don't get library cards—only React components and custom hooks do.

Key Takeaway: Hooks must live inside React function components or custom hooks—never in regular utility functions, classes, or standalone callbacks.