0

I'm getting this dreaded error when I try to use certain packages in my React 18.2.0 create-react-app:

react_devtools_backend.js:2655 Warning: 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://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. 

I've followed all the advice at that link and can't find further help with the Hooks +.... issue. This question has a lot of answers addressing various situations where this error appears, but none seem applicable.

The package causing the problem (at the moment) is react-use, importing a specific function like:

import useMeasure from 'react-use/lib/useMeasure';

It seems likely that the problem was #3, more than one copy of react. But doing npm ls react showed that react-use is using 18.2.0.

I can make the error disappear and reappear by commenting and uncommenting out a single line in a functional react component:

const [ref, measures ] = useMeasure();

I've seen the same problem with several other packages with dependencies on react 18.0, so it seems that the problem is not with react-use specifically.

Sigfried
  • 2,943
  • 3
  • 31
  • 43

1 Answers1

0

As I was writing this question, I was finally driven to make a simple, replicable example. So, I created a new react app (and tried to make sure node, npm, nvm, npx were all up-to-date, deleted my global node_modules and other stuff that might be causing problems), added a little bit of @mui/material to it (because I thought that might be part of the problem) and the package that was currently causing the problem (react-use/lib/useMeasure -- though I'd had the same problem in the past with several other packages with dependencies on react 18.0), and, voila, it all worked. So then I copied ./src of my new example to ./src of my real app, moving its ./src to ./src_hold. It still worked. Then I started copying stuff from .src_hold back to ./src. The problem went away!

I don't know what actually fixed it. Earlier I had tried deleting the app's node_modules and running npm i again, and that hadn't worked. If someone wants to answer this question with a plausible theory about what worked and provide simpler instructions in case someone else comes here with a similar issue, I'll be happy to select it as the proper answer.

Sigfried
  • 2,943
  • 3
  • 31
  • 43
  • https://mdbootstrap.com/support/react/form-giving-error-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/ – Ish May 05 '23 at 13:00