ReactError Fix2026 Updated

React Hooks Can Only Be Called Inside Function Component— Fixed [2026]

Also covers: Invalid hook call · hooks in class components · conditional hooks

January 20265 min readReact 18 · Next.js

⚡ Two Rules of Hooks

1. Only call hooks at the top level of a function component — never in conditions, loops, or nested functions.

2. Only call hooks inside React function components or custom hooks (functions starting with 'use').

The Rules of Hooks

Error
Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

React's reconciliation depends on hooks being called in the same order every render. React uses a linked list internally — hook call 1 maps to slot 1, hook call 2 to slot 2, etc. If the order changes (via conditionals), the slots get shuffled and React loses track of state.

1

Hooks in Class Components

Convert class to function component
3 min
UserProfile.jsx
// ❌ WRONG — hooks cannot be used in class components
class UserProfile extends React.Component {
  render() {
    const [user, setUser] = useState(null)  // Error!
    return <div>{user?.name}</div>
  }
}

// ✅ CORRECT — convert to function component
function UserProfile() {
  const [user, setUser] = useState(null)

  useEffect(() => {
    fetchUser().then(setUser)
  }, [])

  return <div>{user?.name}</div>
}

// ✅ If you must keep a class — use a function component wrapper
function UserProfileWithHooks(props) {
  const theme = useTheme()   // hook in function component
  return <UserProfileClass {...props} theme={theme} />  // pass to class
}
2

Hooks Inside Conditions or Loops

Conditional hook call breaks hook ordering
2 min
component.jsx
// ❌ WRONG — hook inside if block
function Component({ isLoggedIn }) {
  if (isLoggedIn) {
    const [profile, setProfile] = useState(null)  // breaks order!
  }
}

// ✅ CORRECT — hook at top level, condition inside
function Component({ isLoggedIn }) {
  const [profile, setProfile] = useState(null)

  useEffect(() => {
    if (!isLoggedIn) return   // condition INSIDE the hook
    fetchProfile().then(setProfile)
  }, [isLoggedIn])

  if (!isLoggedIn) return null
  return <div>{profile?.name}</div>
}
3

Hooks Inside Callbacks and Event Handlers

Hook called inside a function
2 min
component.jsx
// ❌ WRONG — hook inside an event handler
function SearchBar() {
  function handleSearch() {
    const [results, setResults] = useState([])   // Error!
  }
}

// ✅ CORRECT — hook at component top level
function SearchBar() {
  const [results, setResults] = useState([])  // at top level

  function handleSearch(query) {
    fetchResults(query).then(setResults)  // use the state here
  }

  return (
    <div>
      <input onChange={e => handleSearch(e.target.value)} />
      {results.map(r => <Result key={r.id} result={r} />)}
    </div>
  )
}
4

Duplicate React Versions

Two copies of React in node_modules
3 min

If your code is correct but you still get this error, you may have two copies of React installed. This happens with monorepos or when a local package has its own React dependency.

terminal
# Check for duplicate React
npm ls react
# If you see react listed multiple times → duplicate

# Fix 1 — deduplicate
npm dedupe

# Fix 2 — for linked local packages, resolve to one React
# webpack.config.js
resolve: {
  alias: { react: path.resolve('./node_modules/react') }
}

# Fix 3 — vite.config.js
resolve: {
  dedupe: ['react', 'react-dom'],
}
5

Hook Called in a Non-Component Function

Regular utility function calling a hook
2 min
utils/helpers.js
// ❌ WRONG — hook in a regular function
function formatUserData(userId) {
  const user = useUser(userId)  // Error! Not a component or custom hook
  return user.name.toUpperCase()
}

// ✅ CORRECT — call hook in component, pass value to helper
function formatUserData(user) {  // receives value, no hook
  return user.name.toUpperCase()
}
function UserBadge({ userId }) {
  const user = useUser(userId)  // hook in component
  return <span>{formatUserData(user)}</span>
}

// ✅ ALSO CORRECT — make it a proper custom hook
function useFormattedUser(userId) {  // starts with 'use' → custom hook
  const user = useUser(userId)
  return user?.name.toUpperCase() ?? ''
}
6

Custom Hook Name Must Start With 'use'

React cannot validate hook rules without the prefix
1 min
hooks/userData.js
// ❌ WRONG — doesn't start with 'use', React can't validate
function getUser(id) {
  const [user, setUser] = useState(null)   // will error in strict mode
  useEffect(() => { fetchUser(id).then(setUser) }, [id])
  return user
}

// ✅ CORRECT — starts with 'use' → React treats it as a custom hook
function useUser(id) {
  const [user, setUser] = useState(null)
  useEffect(() => { fetchUser(id).then(setUser) }, [id])
  return user
}

// Usage in component
function Profile({ userId }) {
  const user = useUser(userId)  // ← valid custom hook call
  return <div>{user?.name}</div>
}

The 'use' prefix is not just a convention — React's linter plugin uses it to identify custom hooks and validate that they follow the Rules of Hooks. Always prefix custom hooks with 'use'.

Prevention

Frequently Asked Questions

Why can React hooks only be called inside function components?+
Hooks depend on the order they are called to maintain state between renders. React ties each hook call to a specific slot in the component's internal state array. If hooks are called in a different order (e.g., inside a condition), the slots get misaligned and React cannot track state correctly.
Can I use hooks in class components?+
No. Hooks are only for function components. For class components, use lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) and this.state / this.setState. To use hooks, convert the class to a function component.
Can I call a hook inside an if statement?+
No. Hooks must always be called in the same order on every render. Use conditions inside the hook, not around it: useEffect(() => { if (condition) { doSomething() } }, [condition])
Duplicate React instances causing hook error — how to fix?+
Run: npm ls react in your project. If you see react listed more than once, you have duplicate versions. Fix with: npm dedupe. For monorepos or linked packages, add react to peerDependencies and use npm link or configure your bundler to resolve to one React version.
What is a custom hook and how do I create one?+
A custom hook is a regular JavaScript function that starts with 'use' and calls other hooks inside it. Example: function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => localStorage.getItem(key) ?? initialValue); return [value, setValue]; }
Hook called in a helper function — how to fix?+
Move the hook call to the component level, then pass the value to the helper. Or rename the helper to start with 'use' and make it a proper custom hook. Hooks cannot be called in regular (non-hook) functions.

Need Expert Help?

We Build Production-Grade React Apps

Softplix builds full-stack React and Next.js applications. Need help migrating class components or refactoring hooks? We can help.

Talk to an Engineer