Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Invalid hook call: hooks must run inside a function component

The guard fires when React cannot match a hook call to a render. Duplicate React copies, conditional hooks and version skew are the real causes.

~6 min readReact
#React#Hooks#Testing#Debugging
Two React cubes connected to separate cyan dispatcher rings, an amber hook cable unplugged between them

Introduction & Quick Summary

Invalid hook call. Hooks can only be called inside of the body of a function component. is a runtime guard, not a linter opinion. React throws it when it cannot match a hook call to the render currently in progress, and the message lists the causes it knows: a mismatched React version, a duplicate copy of React, or a hook called outside a component.

The third cause is the rare one. The error almost always resolves to one of these:

  • Two copies of React in the bundle. A linked package or a library that ships its own react dependency installs a second dispatcher, so hooks called through the other copy see null and throw.
  • A hook after an early return or inside a condition, so the hook count differs between renders and the dispatcher's cursor runs past the last hook.
  • A hook called from a plain function. useState inside formatName() is still a hook call.
  • React and React DOM out of step, for example react@19 with react-dom@18 in a monorepo or in tests.
Symptom in the logMost likely causeFirst check
Works in dev, throws from a linked packageDuplicate React copiesnpm ls react
Throws only after a conditional branch rendersHook after early returnHook order in the component
Throws in a utility functionHook outside componentCall site of the utility
Throws only in testsTest renderer uses another React@testing-library/react version
useContext returns null firstMissing provider, then hook orderProvider tree and hook order

Core Mechanics, Signatures & Reproducible Setup

React tracks the current render with an internal dispatcher. Every hook reads from it; outside a render there is none, and the guard throws before the hook does anything. The dispatcher belongs to one React module instance, which is why a second copy is fatal rather than wasteful: the component renders with one and the hook resolves against another.

Reproducing the duplicate-copy failure takes a workspace and one shared package:

bash
mkdir -p packages/ui packages/app && cd packages/ui npm init -y && npm install react@19.1.0 cd ../app npm init -y && npm install react@19.1.0 ../ui
js
// packages/app/index.js import React from "react"; import { useCounter } from "ui"; // ui resolved its own react export function App() { const [count] = useCounter(); // Invalid hook call return React.createElement("p", null, count); }
bash
# one command that usually proves it npm ls react react-dom --all

Two versions or two paths in that output are the whole bug. The hook call is correct; the dispatcher it reads is not the one the render set up.

Key Comparison Table

Each cause has a different repair, and misdiagnosing it is why teams delete node_modules without effect.

CauseWhere it shows upConfirming evidenceRepair
Duplicate ReactMonorepo, linked packagenpm ls react shows two pathsDeduplicate or alias one copy
Hook after a conditionalA component with branchesFails on a later render onlyMove hooks above the branch
Hook in a plain functionUtility or class methodStack trace names a helperConvert to a component or custom hook
Version mismatchreact and react-dom differnpm ls react-dom disagreesPin both to the same version
Two renderers in testsTest imports react-dom/test-utilsFails only under testAlign the test renderer

The duplicate-copy fixes differ by tool, and picking the wrong one leaves the second copy installed.

ToolMechanismScopeWhen to use
overrides (npm)Forces one version in the treeWhole installDuplicates, npm workspaces
resolutions (Yarn)Same, Yarn-specificWhole installYarn 1 or Berry
pnpm.overridesRewrites the graphWhole installpnpm workspaces
peerDependenciesDeclares, does not installPackage boundaryLibrary that must not bundle React
Bundler aliasPoints imports at one copyBuild outputDuplicate survives install

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Deduplicate with overrides and peers

A shared UI package must declare React as a peer, never as a dependency, or it installs its own copy as soon as the versions differ by a patch.

{ "name": "ui", "peerDependencies": { "react": "^19.0.0" }, "devDependencies": { "react": "^19.1.0" } }
{ "overrides": { "react": "19.1.0", "react-dom": "19.1.0" } }

After changing the manifest, delete the lockfile entry and reinstall, then confirm with npm ls react that one version is deduped. npm dedupe only hoists identical versions; it will not merge 19.0.2 and 19.1.0.

Keep hooks above every branch

The rule is about call order, not syntax. A hook inside an if is safe only if the same hooks run in the same order on every render, which in practice means never inside a branch.

jsx
function Profile({ user }) { if (!user) return <p>No user</p>; // early return before hooks const [name, setName] = useState(user.name); return <input value={name} onChange={(e) => setName(e.target.value)} />; }
jsx
function Profile({ user }) { const [name, setName] = useState(user?.name ?? ""); // every render if (!user) return <p>No user</p>; return <input value={name} onChange={(e) => setName(e.target.value)} />; }

Deriving initial state from a possibly missing user is the real fix. Guarding the hook itself compiles and then fails on the render where the branch changes.

Turn helpers into custom hooks

A function that calls hooks is a hook and must be named use* so the linter and React both treat it as one. Calling such a helper from an event handler is a hook call outside a render, whatever its name.

js
function useFake() { return useState(0); } function Counter() { const [count] = useFake(); return <button onClick={() => useFake()}>click</button>; // Invalid hook call }
js
function useCounter(step = 1) { const [count, setCount] = useState(0); const increment = useCallback(() => setCount((c) => c + step), [step]); return { count, increment }; } function Counter() { const { count, increment } = useCounter(); return <button onClick={increment}>{count}</button>; }

Hooks read state; handlers change it. A handler that needs a hook result receives it as an argument or closure, not by calling the hook again.

Align react and react-dom in a monorepo

React 19 moved internals and removed react-dom/test-utils. A package that still loads react-dom@18 while the app runs react@19 hits the guard on the first useState, because the renderer sets up dispatchers for a different React instance.

bash
npm ls react react-dom react-test-renderer @testing-library/react
{ "dependencies": { "react": "19.1.0", "react-dom": "19.1.0" }, "devDependencies": { "@testing-library/react": "16.3.0" } }

Testing Library 16 supports React 19; older versions import the removed test utilities and fail as an invalid hook call inside the first test.

Bundler aliases when the duplicate survives install

Sometimes the graph is correct and the bundle still contains two copies, for example when a prebuilt dependency bundles React or a path alias resolves to a second install.

js
// vite.config.js export default defineConfig({ resolve: { dedupe: ["react", "react-dom"], alias: { react: "/node_modules/react" } } });
js
// next.config.js module.exports = { webpack(config) { config.resolve.alias = { ...config.resolve.alias, react: require.resolve("react") }; return config; } };

Log React.version from the app and from the shared package. If the values differ, the bundle still has two copies regardless of what the lockfile says.

A missing provider is a different error

useContext on a missing provider returns the default, often null, and the crash that follows looks like a hook problem but is a provider problem.

jsx
const ThemeContext = React.createContext(null); function Button() { const theme = useContext(ThemeContext); // null, not an invalid hook call return <button className={theme.className}>…</button>; // TypeError }
jsx
function Button() { const theme = useContext(ThemeContext); if (!theme) throw new Error("Button must render inside ThemeProvider"); return <button className={theme.className}>…</button>; }

Reading the error text matters: Invalid hook call and Cannot read properties of null are different failures with different fixes.

Common Compilation/Runtime Mistakes & Version Gotchas

Calling hooks from class components. Hooks do not exist there. The error appears when a class method calls a function containing hooks; convert the component or lift the state.

useMemo as an escape hatch for side effects. useMemo(() => fetch(url), [url]) runs during render and can be dropped by React, so the fetch may never happen or may happen twice. Effects belong in useEffect.

Ignoring the hook lint rules. eslint-plugin-react-hooks catches conditional hooks before the runtime guard. Disabling it because "it complains about my helper" hides the case where the helper genuinely breaks call order.

Assuming StrictMode is the cause. StrictMode double-invokes render in development to surface impure code, which produces duplicate logs, not an invalid hook call.

Version notes. React 19 removed react-dom/test-utils; tests importing act from it fail with a module error or an invalid hook call. useSyncExternalStore and useId are the SSR-safe replacements for subscription and id patterns that used to live outside components. Custom hooks must start with use since the React 17 lint rules, and the dispatcher guard itself is unchanged from React 16.

Triage order: npm ls react react-dom, then hook order in the failing component, then a search of the built bundle for a second React banner. When comparing two lockfiles or two stack traces, the text diff keeps the version lines readable, and the JSON formatter confirms which React version each manifest actually resolves.

Official references: Invalid hook call warning and Rules of Hooks.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.