next.js: Invalid hook call in 9.0.6
Bug report
Describe the bug
When you use react a component residing outside the main Next.js project folder which uses hooks. You end up getting Invalid hook call error and the application breaks. Components without hooks work as expected.
The bug appears in all versions >9.0.5 when you change the webpack config so that files outside the main folder are transpiled. It’s working fine in <=9.0.5
To Reproduce
Check out the repro at https://github.com/baldurh/next-9.0.6-bug-repro
Expected behavior
The code should not break when using files outside the project folder.
System information
- OS: N/A
- Browser: N/A
- Version of Next.js:
>=9.0.6
Additional context
I know this is probably not a common use of Next.js but in our project we’re using a monorepo and have a shared folder with components used by multiple applications. It would be nice to get this working again. If someone finds an alternative config we could use I’d also be happy to do that 🙂
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 84
- Comments: 99 (29 by maintainers)
Commits related to this issue
- Allow libs that ends with `next/dist` such as `i18next`, `next-i18next`, `react-i18next` to be external (#9956) fixes #9022 Co-authored-by: Joe Haddad <timer150@gmail.com> — committed to vercel/next.js by felixmosh 7 years ago
- Fix #55 by moving react & react-dom dependencies one level up This is a workaround for Next's https://github.com/vercel/next.js/issues/9022#issuecomment-559622803 — committed to NOtherDev/nest-next by NOtherDev 6 years ago
- Fix #55 by moving react & react-dom dependencies one level up This is a workaround for Next's https://github.com/vercel/next.js/issues/9022#issuecomment-559622803 — committed to NOtherDev/nest-next by NOtherDev 6 years ago
- Move QueueModal into podverse-web to avoid local "invalid hooks" crash I couldn't figure out how to solve this properly, so as a workaround I'm moving the react-beautiful-dnd module into podverse-web... — committed to podverse/podverse-ui by mitchdowney 6 years ago
- Move QueueModal into podverse-web from podverse-ui I couldn't figure out how to solve this properly, so as a workaround I'm moving the react-beautiful-dnd module into podverse-web. More info: https:... — committed to podverse/podverse-web by mitchdowney 6 years ago
I have a monorepo with a next.js project inside. Faced the same issue with an invalid hook call after installing
storybook. Got the issue resolved by following @aengl’s suggestion – I added theresolutionsto the root levelpackage.json:I’m not sure if that’s going to be a good solution once we’re adding more clients and packages though.
Hi any update on this issue? We have a monorepo and we are encountering this exact issue.
@baldurh This is indeed very uncommon, when using platforms like Now only the folder where the Next.js app lives is deployed, it’s better that way because otherwise you would need to know about all the external modules first. 2 better alternatives are:
I’m also having this issue using
npm linkto a component library during development that has asdevDependencyReact. Usually this it’s pretty simple to fix, justaliasin the webpack config for the duplicated packages but it’s not working with Next.jsok I had a very stupid error causing this issue:
It should be react instead of React:
By the way, to anyone experiencing this issue when using
next-transpile-modulesandnpm, I wrote a FAQ section that explain the problem and potential solutions: https://www.npmjs.com/package/next-transpile-modules#i-have-trouble-with-duplicated-dependencies-or-the-invalid-hook-call-error-in-reactI haven’t had time to dig into this yet, but if anyone needs a repro: clone next-i18next,
cdintoexamples/simpleand upgrade the NextJs version to >=9.0.6.It’s currently on 9.0.3, so this is technically a breaking change on a patch.
Thank you for posting this issue, I also had problems with symlinking our design system (react component library) package. We are also transpiling it using https://github.com/martpie/next-transpile-modules.
The fix as suggested here worked for us:
node_modulesfolder (we did it with our own utility instead ofnpm linkbut should basically be the same)next.config.js:Our alternative workaround that requires no config
node_modulesfrom your package. I created my own utility for this can maybe post it on github.But would be nice to see this fixed in NextJS, I spent so much time trying to understand why webpack alias worked for all my non NextJS project 😃
I’m trying to use a linked package and I’m experiencing the same issue. Sadly none of the fixes from https://github.com/facebook/react/issues/13991 work 🙁
@timneutkens @Timer sorry for tagging you in this but I’d love some input from you. Do you think this is something that could be fixed do we all need to implement some workarounds? This is a pretty big blocker for us at the moment. Thanks.
I managed to solve this by manually adding the version resolution for yarn in the project root. So instead of moving all react dependencies to the root
package.json, I added the following lines:See: https://classic.yarnpkg.com/en/docs/selective-version-resolutions/
It’s worth noting that in my case, local builds worked whereas builds on Vercel reported the
Invalid hook callerror.I can confirm that this is related to the PR https://github.com/vercel/next.js/pull/8739 by @arcanis We are using a monorepo setup with Rush and pnpm which eliminates the reason the mentioned PR was merged. It also means that the point that @timneutkens made in https://github.com/vercel/next.js/issues/9022#issuecomment-610255555 does not apply to us, we have the following structure:
The
library.devDependencies.(react|react-dom)are symlinks that point to the exact same files as thewebsite.dependencies(react|react-dom). However it looks like resolve@1.11.0 that is used in the https://github.com/vercel/next.js/blob/f98e38c9b634b85e6679e7b5f953a9d98074cfc3/packages/next/lib/resolve-request.ts#L16 does not follow the current default Node.js behaviour by preserving the symlinks.We ended up with the following:
libraryresolve.symlinks = truein the webpack config inside of thenext.config.jslibraryto be requested from thelibrary/node_modules(for the server-side build to resolve modules correctly)This works as intended but feels hacky, given that Next.js is powering some of the important websites like Apple’s is it possible to expect better support for the monorepos that are often used to manage shared code in those big projects?
Thanx for the explanation, I will wait for Next team to solve it, sounds a bit weird to put react deps on the root of my mono-repo…
This works for us as well but it breaks styled-components on SSR 😞
I experimented a similar issue in
_app.jswith a catchall page in Next 10I’m glad that worked for you but I doubt many people in this thread have these dependencies globally installed.
Running into the same issue, and bringing
reactandreact-domone level up and running the server from the root is the only workaround that works currently on 9.1.5. Linking https://github.com/facebook/react/issues/13991 and https://github.com/facebook/react/issues/15315#issuecomment-479802153 for reference as I found those links before this issue.@lfades thanks for the reply. Neither of those options are available to us and we’re not deploying to Now or anything similar. We used yarn workspaces initially but then we integrated bazel and it does not play nicely with the symlinking nature of yarn workspaces. Npm packages means we cannot develop the shared modules as fast as we like. It’s just too much overhead.
This worked for me
https://www.npmjs.com/package/next-transpile-modules#i-have-trouble-with-duplicated-dependencies-or-the-invalid-hook-call-error-in-react
@jcpsimmons What error do you get?
I think what you actually need is something like this:
I can confirm the same experience as @wasd171 in a Rush + PNPM monorepo. I’ll just use
~9.4.4in the interim.I resolve my issue using https://github.com/vercel/next.js/issues/9022#issuecomment-609969178 as a solution. My issues was with using my library repo and
yarn linking it with my app repo example package.jsonand I
yarn link myUILibraryto my locally checkoutMyRepo/library-web-uiwhich also hasreactinstalled.Thanks a lot @johot for posting your solution
5 🌟 out of 3 (yes! All the stars and more!)
Folks, simple fix, remove your global version of react, next and react-dom by doing:
npm remove -g react next react-domIf you are using
next-transpile-modulesand Yarn, the solution is quite straightforward: https://github.com/martpie/next-transpile-modules#i-have-trouble-with-duplicated-dependencies-or-the-invalid-hook-call-error-in-reactIf you are using
npm, I am still myself looking for a solution :c@timneutkens
Well no this is not always the case. I for sure has react and react-dom as peer dependencies. The problem still occurs though if you for example symlink your library to a nextjs project. What then happens is that you will have a
node_modulesfolder inside your library (at least if you ever rannpm iornpm linkin that library folder).When react gets resolved from this library folder it will resolve to the one in that
node_modulesfolder and you get dual copies of react causing the problem. If I delete thenode_modulesfolder inside my lib or install it using something else thannpm linkthen yes ofc it works (if you use peer dependencies or exactly the same react version).So to solve this during dev you want to be able to alias react to force everyone to use the same version. Because of the problems mentioned here this has no effect in the current NextJS version without adding the
config.externals ...part (at least for me), probably as people have mentioned here because of some change as noted here #8739 ?I’m also experiencing the same issue with a component library symlinked with
yarn link. This worked fine up untilv9.0.6-canary.4and now I’m in the same position as some other commenters and cannot upgrade past this… I have pin-pointed the change to this PR https://github.com/zeit/next.js/pull/8739My component library uses
react,react-dom, andstyled-components. The configuration for this is as followsUpdate
I was able to fix this by including these modules in the server externals. Thanks to @HosseinAgha in this comment https://github.com/martpie/next-transpile-modules/issues/50#issuecomment-558318688
For me the main issue is the new way requests are resolved: https://github.com/zeit/next.js/blob/canary/packages/next/build/webpack-config.ts#L446
Since we have components outside the project root the request resolution will throw an error which results in
reactbeing bundled in the server chunks. And that’s why we get theInvalid hook callerror on the server.I was able to resolve this just now in the repro by moving the
reactandreact-domdependencies one level up. I just pushed the changes if anyone wants to try it out. I haven’t tried it on our actual project but I’m hopeful it will work for us. Perhaps this could solve the issue for @isaachinman, @jaredcwhite and @felixmosh as well?@baldurh Just ran into this with next-i18next as we’ve got nested NextJs apps as examples. Did you find a workaround?
thank you this did wonders and liberated me from the misery i have been entailing
This is exhausting
export function useWindowDimensions() { const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => { function handleResize() { setWindowDimensions(getWindowDimensions()); }
}, []);
return { windowDimensions }; }
creating simple hook in Nextjs is throwing hook error
I can’t reason as to why this might work, but for me, the only thing that ended up resolving the issue was running
yarn global remove next(I had previously installed next globally), and then runningnext devin the project folder again.Hey,
In my case I had transpiled modules that were also linked via
npm link.Dependencies like React need to be included as
peerDependenciesinstead of regular dependencies because it was downloading multiple instances of it. So if you’re having the invalid hooks error, try these steps:npm installto get all your modules installed.sudo npm link.npm link @example/project. You should see a little arrow icon near your module name inside node_modules if you’re using Visual Studio Code.npm run dev.Again, you must include React as a peerDependency instead of a regular dependency in your @example/project.
I hope that helps!
FYI, it was one of the reasons why my org decided to move from
npmtoyarn. It just (unfortunately) plays much nicer. The move is annoying, but we’re quite happy now.hey @Timer is there a progress on this?
Is there a solution for this at all?
Just completely stuck with version 9.4.4.
Issue happening on HOC for private routes below. I also tried using
withRouterbut then the same error is thrown on the wrapped component instead.Strangely, using
resolve.aliasdoes not seem to affect packages outside the project root.Here’s my
next.config.jsfile:I’m using
yarn linkwith a local package that exists in a Lerna monorepo. Itsnode_modulesdoes not contain a copy ofreact, but the monorepo root does. I wouldn’t expect that to make a difference as long asresolve.aliasis used, but that’s unfortunately not the case. After removing the copy ofreactfrom the monorepo root, I’m now getting aCannot find module 'react'error instead.I think that I’ve found the issue!!! I think that it is a combination of 2 things:
i18next/react-i18nextwere not external in server bundles!!useTranslationhook…So i’ve investigated the reason for why there are node modules inside server bundles at all (best practice for server bundles is to make them externals).
I saw that next has some exceptions for next lib (why?), the funny part is that this regex catches all libs that ends with
next/dist/, asi18next&react-i18nextdoes!!So, if you change this:
into
The server bundle will exclude all libs that are not
next& ends withnext/dist, and it solved the issue!@felixmosh Yeah I kind of agree with you. However, if you use something like yarn workspaces that’s exactly what that tool will do. If you have the same dependency in two or more projects it will hoist the dependencies to the root. It’s nice because it ensures that you have the same version of the dependencies in all your projects. But if you don’t have a tool like that you’d have to manage it yourself which is indeed a bit awkward. I agree the best solution would be that the Next.js team takes a look and solves this for all of us 😇🙏🏻
Ah, yes. Improperly published
node_modulepackages will cause this (with dependencies onreact(-dom|)instead of peer dependency).@Timer I got this working in our project but I also had to make sure I had no other dependencies which installed
reactinto our projects’node_modulesfolder. In our case it was related to storybook (yarn why reacthelped a lot 😄). We were planning to move storybook to a separate project anyway so I think this solution will work in our case.