To fix React’s "Invalid hook call. Hooks can only be called inside the body of a function component" error, verify that hooks (useState, useEffect, useRef, useMemo, useCallback, or custom use* hooks) are called unconditionally at the top level inside a React function component or custom hook (never inside loops, if/else branches, event handlers, class components, or plain helper functions), ensure only a single copy of react is loaded across your app and linked/bundled dependencies (npm ls react and bundler aliases), and guard inputs, state transitions, and diagnostics with typeof / instanceof / Array.isArray checks, a Map, and try / catch blocks.
1. Calling Hooks Only Inside Function Components or Custom Hooks (Top-Level Only)
React tracks hook calls by positional call index during a render; calling hooks conditionally, inside callbacks/event handlers, or outside React’s render tree causes an invalid hook call:
// Custom hook and function component calling hooks unconditionally at top level
function useMapCounter(initialPairs = [["clicks", 0]]) {
if (!Array.isArray(initialPairs)) {
throw new TypeError("Expected initialPairs to be an Array instance.");
}
const [countsMap, setCountsMap] = React.useState(() => {
try {
const map = new Map();
for (let i = 0; i < initialPairs.length; i += 1) {
const pair = initialPairs[i];
if (!Array.isArray(pair) || pair.length < 2) {
throw new TypeError(`Expected entry at index ${i} to be a [key, count] tuple.`);
}
const [key, count] = pair;
if (typeof key !== "string" || key.trim().length === 0) {
throw new TypeError(`Expected key at index ${i} to be a non-empty string.`);
}
if (typeof count !== "number" || !Number.isInteger(count)) {
throw new TypeError(`Expected count at index ${i} to be an integer.`);
}
map.set(key.trim(), count);
}
return map;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed initializing countsMap: ${message}`);
}
});
const incrementCounter = React.useCallback((metricKey) => {
if (typeof metricKey !== "string" || metricKey.trim().length === 0) {
throw new TypeError("Expected metricKey to be a non-empty string.");
}
setCountsMap((prevMap) => {
try {
const safePrev = prevMap instanceof Map ? prevMap : new Map();
const cleanKey = metricKey.trim();
const nextMap = new Map(safePrev);
const currentValue = nextMap.get(cleanKey) ?? 0;
nextMap.set(cleanKey, currentValue + 1);
return nextMap;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Failed incrementing "${metricKey}": ${message}`);
return prevMap;
}
});
}, []);
return { countsMap, incrementCounter };
}
function CounterButton({ metricKey = "clicks" }) {
const { countsMap, incrementCounter } = useMapCounter([[metricKey, 0]]);
// Event handlers run after render—never call hooks inside here
const handlePress = () => {
try {
incrementCounter(metricKey);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`Button press error: ${message}`);
}
};
const currentCount = countsMap instanceof Map ? (countsMap.get(metricKey) ?? 0) : 0;
return React.createElement(
"button",
{ type: "button", onClick: handlePress },
`${metricKey}: ${currentCount}`
);
}
- Never call hooks inside
if,else,for,while,try / catch, or event/DOM callbacks: Hook execution order must stay identical on every render. - Prefix custom hooks with
use(useAuth,useFormState): Lets React hook linters verify rules of hooks across custom hook functions.
2. Auditing Duplicate react Copies and Dispatcher Availability with a Map
When a hook call fails due to duplicate/mismatched react copies (common in monorepos, npm link / yarn link local packages, or misconfigured bundler aliases), record diagnostic checks in a Map inside try / catch:
// Diagnose common causes of React "Invalid hook call" into a Map
function inspectHookEnvironment({
reactRef = (typeof React !== "undefined" ? React : null),
hasConditionalOrNestedCall = false,
hasDuplicateReactCopies = false
} = {}) {
if (typeof hasConditionalOrNestedCall !== "boolean") {
throw new TypeError("Expected hasConditionalOrNestedCall to be a boolean.");
}
if (typeof hasDuplicateReactCopies !== "boolean") {
throw new TypeError("Expected hasDuplicateReactCopies to be a boolean.");
}
try {
const isReactObject = typeof reactRef === "object" && reactRef !== null;
const hasUseState = isReactObject && typeof reactRef.useState === "function";
const causes = [];
if (hasConditionalOrNestedCall) {
causes.push("Hook called conditionally, inside a loop, inside an event handler, or outside a function component/custom hook");
}
if (hasDuplicateReactCopies) {
causes.push("Multiple copies of React present (such as linked packages or monorepo hoisting mismatches)");
}
if (!hasUseState) {
causes.push("React hook dispatcher missing or invalid React reference in scope");
}
return new Map([
["reactObjectValid", isReactObject],
["useStateAvailable", hasUseState],
["likelyCauses", causes],
["inspectCommand", "npm ls react"]
]);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed inspecting React hook environment: ${message}`);
}
}
// Example usage:
// try {
// const reportMap = inspectHookEnvironment({ hasDuplicateReactCopies: true });
// console.log("Diagnostic causes:", reportMap.get("likelyCauses"));
// } catch (error) {
// console.error(`${error.name}: ${error.message}`);
// }
- Use
Mapfor diagnostic fields: Prevents collisions withObject.prototypeproperties (constructor,toString,hasOwnProperty). - Run
npm ls reactto detect duplicate versions: Ensure only one copy ofreactresolves at runtime and aliasreact/react-domin bundler configs when linking local packages.
3. Rules of Hooks, Version Alignment, and Immutable State Caveats
Keep these React hook rules and pitfalls in mind in production code:
- Keep
reactandreact-domon matching versions: Version mismatches betweenreactandreact-domcan break hook dispatchers. - Render components with JSX or
React.createElement(Component), notComponent(): Calling a component function directly bypasses React’s component fiber context. - Return a new
Mapinstance when updatingMapstate: Mutating an existingMapin place and passing the same reference can skip re-renders when React compares previous and next state.
