日本語

Fixing “Invalid hook call” in React

​​React​Troubleshooting,TypeScript,useState,Vite

The Invalid hook call error in React mainly happens in two cases. One is when a hook such as useState is called inside an ordinary function like an event handler, or outside a component. The other is when two copies of React end up in the app, for example after installing a component library you developed in a separate folder. The first case is fixed by moving the hook call to the right place, and the second case goes away once there is only one copy of React.

I reproduced each case in a test environment, recorded the error messages from the console, and confirmed that the error disappears after the fix.

Note

The test environment was Ubuntu 24.04 and Node.js 22.23.4. I used a project created from the react-ts template of npm create vite@latest (react and react-dom 19.3.1, Vite 8.3.8, TypeScript 7.0.2, oxlint 1.93.0), and wrapped the components in StrictMode. I opened the pages in Chromium 153 driven by Playwright 1.63.0, and took the DevTools screenshots with a headed Chromium running on a virtual display (Xvfb). I did not test Next.js or other frameworks, bundlers other than Vite such as webpack, browsers other than Chromium, the eslint-plugin-react-hooks package with ESLint, or opening the dev server after running npm link.

The full error message in the console

When I opened a page with a hook called in the wrong place on the development server (vite, the same command as npm run dev), the DevTools console showed the following error.

text
Uncaught 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
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.

The message means "Hooks can only be called inside the body of a function component." It then lists three possible causes: the versions of React and React DOM do not match, the Rules of Hooks are broken, or the same app has more than one copy of React. In this article, I reproduced the second and third causes.

Calling a hook inside an event handler

The following component calls useState inside handleClick, a function that runs when the button is clicked.

tsx
import { useState } from 'react';

// Wrong: the hook is called inside a function that runs on click (an event handler)
export default function BadHandler() {
  function handleClick() {
    const [count, setCount] = useState(0);
    setCount(count + 1);
  }
  return <button onClick={handleClick}>押す</button>;
}

This page does not throw an error just by being opened. The button appears, and the error appeared in the console the moment I clicked it. Each click added one more error, and the button's display did not change.

The DevTools console shows, in a red line, "Uncaught Error: Invalid hook call." followed by the three-cause text. Below it is "at handleClick (BadHandler.tsx:6:31)". The page above shows a button labeled "Press" (the label is in Japanese in the original screenshot).
After clicking the button once. The function that called the hook and its file line appear under the error.

Under the error, DevTools showed at handleClick (BadHandler.tsx:6:31), which gives the name of the function that calls useState and the file line. The error text alone does not say where the problem is, so this line is the first place to look.

The official documentation on the Rules of Hooks says that hooks may only be called at the top level of a function component or a custom hook. Calling a hook inside an event handler is listed as an example of what not to do. To fix it, move useState to the top of the component body and use only the setter function in the handler.

tsx
import { useState } from 'react';

// Fixed: the hook is called at the top of the component body, and the handler only uses the setter
export default function GoodHandler() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);
  }
  return <button onClick={handleClick}>押す({count}回)</button>;
}

On the fixed page, clicking the button produced no error, and the label changed from "Press (0 times)" to "Press (1 times)" and "Press (2 times)".

Calling a hook outside a component

If a hook is called at the top of a file, outside any function, the same Invalid hook call. message appears.

tsx
import { useState } from 'react';

// Wrong: the hook is called outside a component (at the top of the file)
const [theme, setTheme] = useState('light');

export default function BadTopLevel() {
  return <button onClick={() => setTheme('dark')}>テーマ: {theme}</button>;
}

Here useState runs as soon as the file is loaded. In my test, the page threw an error just by being opened, and the screen was blank (the <div id="root"> that holds the component was empty).

However, how the error appeared in the console depended on how the file was loaded. When the entry file of the app (in my test, static-main.tsx, separate from main.tsx) imported it with a normal import BadTopLevel from './BadTopLevel', the Invalid hook call. message was logged as an error, and then the following error was thrown.

text
Uncaught TypeError: Cannot read properties of null (reading 'useState')

When the file for the page was loaded with React's lazy, the same Uncaught Error: Invalid hook call. as before was thrown, and the following warning also appeared.

text
An error occurred in one of your React components.

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.

Normally this warning includes the name of the component where the error happened. Here it says "one of your React components," so the name does not tell you where to look. In both loading methods, the error stack showed the file name and line of BadTopLevel.tsx, so I used that to find the problem.

To fix it, move useState inside the component.

tsx
import { useState } from 'react';

// Fixed: moved inside the component
export default function GoodTopLevel() {
  const [theme, setTheme] = useState('light');
  return <button onClick={() => setTheme('dark')}>テーマ: {theme}</button>;
}

On the fixed page, there was no error, the page showed "Theme: light", and clicking the button changed it to "Theme: dark".

An ordinary function called during render does not raise an error

When a hook is called inside an ordinary function, but that function is called while the component renders, I did not get an error. The following component displayed a greeting on the page, and no error appeared in the console.

tsx
import { useState } from 'react';

// A hook is called inside a regular function whose name does not start with "use", and that function is called during render
function getLabel() {
  const [label] = useState('こんにちは');
  return label;
}

export default function HelperInRender() {
  return <p>{getLabel()}</p>;
}

However, this also breaks the Rules of Hooks. The official documentation says hooks may only be called from function components and from custom hooks, whose names start with use. If you want to treat a function as a custom hook, rename it so it starts with use, such as useLabel. The body stays the same, and the page displayed the same greeting.

tsx
// Fixed: renamed so it starts with "use" and is treated as a custom hook
function useLabel() {
  const [label] = useState('こんにちは');
  return label;
}

export default function GoodHelper() {
  const label = useLabel();
  return <p>{label}</p>;
}

Catching these with oxlint before opening the browser

All three mistakes above are valid TypeScript, so npx tsc -p tsconfig.app.json --noEmit did not report any errors. The oxlint linter included in the template, however, caught all three. This is because the template's configuration (.oxlintrc.json) sets react/rules-of-hooks to error. Running npx oxlint src printed the following.

text
src/BadTopLevel.tsx:4:27: error react-hooks(rules-of-hooks): React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.
src/BadHandler.tsx:6:31: error react-hooks(rules-of-hooks): React Hook "useState" is called in function "handleClick" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".
src/HelperInRender.tsx:5:19: error react-hooks(rules-of-hooks): React Hook "useState" is called in function "getLabel" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".

It also flagged getLabel, which did not raise an error at runtime. If your project uses ESLint, you can check the same rules with eslint-plugin-react-hooks, which the official documentation recommends.

When two copies of React are installed

Even when hooks are written correctly, having two copies of React causes the same kind of error. In my test, I created a component package my-button in a separate folder and installed it into the app with npm i ../my-button. my-button is a button that counts clicks with useState. Its package.json lists react under dependencies, and I also ran npm i in that folder.

Running npm ls react in the app folder showed another react under my-button (paths are replaced with example values).

text
app@0.0.0 /path/to/app
+-- my-button@1.0.0 -> ./../my-button
| `-- react@19.3.1
+-- react-dom@19.3.1
| `-- react@19.3.1 deduped
`-- react@19.3.1

According to the official documentation on the Invalid hook call warning, hooks only work when the react imported by the app's code and the react imported inside react-dom are the same object. In this setup, import { useState } from 'react' inside my-button can resolve to a different react in my-button's own node_modules, not the one the app uses. In my build, that is what happened.

It did not happen on the dev server, but it did in the build

When I opened the page on the development server, the button worked and there was no error. Looking at how the dev server transformed the files in my-button, the react imports had been rewritten to the app-side /node_modules/.vite/deps/react.js produced by Vite's dependency pre-bundling. In other words, the dev server had merged React into one copy.

However, when I built for production with npx vite build and opened the result with npx vite preview, the page was blank and the only error was the following.

text
Cannot read properties of null (reading 'useState')

The production build does not print the Invalid hook call message. To check that message, I built a development version with NODE_ENV=development npx vite build --mode development --minify false --outDir dist-dev and opened it. The console then showed the following. The same message appeared twice, followed by a TypeError.

text
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
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.
text
Uncaught TypeError: Cannot read properties of null (reading 'useState')

The warning that followed included An error occurred in the <CountButton> component., which is the name of the component in my-button.

The DevTools console shows, in a red line, "Uncaught TypeError: Cannot read properties of null (reading 'useState')" with its stack. A yellow line reads "An error occurred in the <CountButton> component." The error counter at the top right shows 3. The page above displays nothing.
The development build with two copies of React installed. The last TypeError and the warning are visible among the three errors.

The fact that a TypeError is thrown after the logged error is the same as the top-level case with a normal import, and differs from the event handler case. Looking at the development build of react 19.3.1, the message is printed in two places. useState and the other hooks in react check the slot (ReactSharedInternals.H) that react-dom uses to provide the hook implementation. If that slot is null, the message is logged and execution continues. Then reading useState from null throws the TypeError. When the slot holds react-dom's ContextOnlyDispatcher, the hook function itself (throwInvalidHookError for useState and the others) throws the message. The stack for the top-level call in the lazy-loaded file included this throwInvalidHookError. With two copies of React, the slot belonging to the react that my-button uses stayed null, which caused the TypeError.

Searching the built development files, I found react.development.js in two places.

text
dist-dev/assets/UseMyButton-BNdzeMvA.js:2:// ../my-button/node_modules/react/cjs/react.development.js
dist-dev/assets/index-CTd_yjxt.js:33:// node_modules/react/cjs/react.development.js

Merging into one copy with resolve.dedupe in Vite

If you use Vite, you can set resolve.dedupe in vite.config.ts to make the listed packages resolve to the copy in the project root, no matter where they are imported from.

ts
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    // Use the react in the project root, wherever it is imported from
    dedupe: ['react', 'react-dom'],
  },
})

After rebuilding with this setting, the development build contained only one react.development.js. Neither the production nor the development build showed any error, and clicking the button increased the count from "Count: 1" to "Count: 2".

On the fixed page, the button shows "Count: 1". The DevTools console below it shows only one line, the React DevTools notice.
After rebuilding with resolve.dedupe and clicking the button once. No error is shown.

Using the app's React with npm link

The official documentation also describes a fix for linked libraries: run npm link ../myapp/node_modules/react from the library folder. This makes the library use the same React as the app.

I restored vite.config.ts and ran npm link ../app/node_modules/react in the my-button folder. my-button/node_modules/react then became a link to the app's node_modules/react. After rebuilding the development version, there was only one react.development.js, there was no error, and the button counted clicks.

The official documentation also lists, as an example cause of two copies of React, a library that declares react in dependencies instead of peerDependencies.

If you see #321 on a production site

When I built the page that called a hook inside an event handler for production and opened it, the error on button click showed only a number.

text
Minified React error #321; visit https://react.dev/errors/321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

In the table that maps error numbers to messages in the React repository, error 321 is the Invalid hook call. message discussed in this article. If you see #321 on a live site, check where hooks are called. When there are two copies of React, the production build showed only Cannot read properties of null (reading 'useState'), as described above, so if you see a TypeError of this form, run npm ls react to check how many copies of React are installed.

​Posted by 86