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.

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
reactdependency installs a second dispatcher, so hooks called through the other copy seenulland 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.
useStateinsideformatName()is still a hook call. - React and React DOM out of step, for example
react@19withreact-dom@18in a monorepo or in tests.
| Symptom in the log | Most likely cause | First check |
|---|---|---|
| Works in dev, throws from a linked package | Duplicate React copies | npm ls react |
| Throws only after a conditional branch renders | Hook after early return | Hook order in the component |
| Throws in a utility function | Hook outside component | Call site of the utility |
| Throws only in tests | Test renderer uses another React | @testing-library/react version |
useContext returns null first | Missing provider, then hook order | Provider 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:
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// 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);
}# one command that usually proves it
npm ls react react-dom --allTwo 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.
| Cause | Where it shows up | Confirming evidence | Repair |
|---|---|---|---|
| Duplicate React | Monorepo, linked package | npm ls react shows two paths | Deduplicate or alias one copy |
| Hook after a conditional | A component with branches | Fails on a later render only | Move hooks above the branch |
| Hook in a plain function | Utility or class method | Stack trace names a helper | Convert to a component or custom hook |
| Version mismatch | react and react-dom differ | npm ls react-dom disagrees | Pin both to the same version |
| Two renderers in tests | Test imports react-dom/test-utils | Fails only under test | Align the test renderer |
The duplicate-copy fixes differ by tool, and picking the wrong one leaves the second copy installed.
| Tool | Mechanism | Scope | When to use |
|---|---|---|---|
overrides (npm) | Forces one version in the tree | Whole install | Duplicates, npm workspaces |
resolutions (Yarn) | Same, Yarn-specific | Whole install | Yarn 1 or Berry |
pnpm.overrides | Rewrites the graph | Whole install | pnpm workspaces |
peerDependencies | Declares, does not install | Package boundary | Library that must not bundle React |
| Bundler alias | Points imports at one copy | Build output | Duplicate 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.
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)} />;
}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.
function useFake() {
return useState(0);
}
function Counter() {
const [count] = useFake();
return <button onClick={() => useFake()}>click</button>; // Invalid hook call
}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.
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.
// vite.config.js
export default defineConfig({
resolve: {
dedupe: ["react", "react-dom"],
alias: { react: "/node_modules/react" }
}
});// 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.
const ThemeContext = React.createContext(null);
function Button() {
const theme = useContext(ThemeContext); // null, not an invalid hook call
return <button className={theme.className}>…</button>; // TypeError
}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 documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact: An update inside a test was not wrapped in act(...)
The warning means a state update escaped the test's act scope. Await the interaction, use findBy queries, and wrap manual updates properly.
React: Cannot update a component while rendering a different component
The warning means one component scheduled state for another during render. Derive the value or move the write to a handler.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Compiler: Cannot reassign variable after render completes
The immutability rule flags a closure that writes a render-scoped value. Decide whether it is a real bug, a false positive, or a bailout.
More in React
All React guidesThe guides filed next to this one in React, in library order.