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

Most upvoted comments

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 the resolutions to the root level package.json:

"resolutions": {
  "react": "^17.0.1",
  "react-dom": "^17.0.1"
}

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:

  • Move everything to a single Next.js app
  • Use lerna or private npm packages or similar

I’m also having this issue using npm link to a component library during development that has as devDependency React. Usually this it’s pretty simple to fix, just alias in the webpack config for the duplicated packages but it’s not working with Next.js

ok I had a very stupid error causing this issue:

import React, { useState } from 'React';

It should be react instead of React:

import React, { useState } from 'react';

By the way, to anyone experiencing this issue when using next-transpile-modules and npm, 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-react

I haven’t had time to dig into this yet, but if anyone needs a repro: clone next-i18next, cd into examples/simple and 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:

  • Symlink your library to your node_modules folder (we did it with our own utility instead of npm link but should basically be the same)
  • Add something like the following to your next.config.js:
// next.config.js
const nextConfig = {
	webpack: (config, options) => {
		// modify the `config` here

		if (options.isServer) {
			config.externals = ["react", ...config.externals];
		}
		config.resolve.alias["react"] = path.resolve(__dirname, ".\\node_modules\\react");

		return config;
	},
};
// more plugins etc...

Our alternative workaround that requires no config

  • Symlink everything except the node_modules from 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 😃

PS. I have no idea how this would affect a production build but we would only use this during dev

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:

  "resolutions": {
    "react": "16.13.1",
    "react-dom": "16.13.1"
  }

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 call error.

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:

website
  dependencies: next, react, react-dom, library
library
  devDependencies: react, react-dom (for tests)
  peerDependencies: react, react-dom

The library.devDependencies.(react|react-dom) are symlinks that point to the exact same files as the website.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:

  1. Setting up the next-transpile-modules to transpile our code in library
  2. Setting resolve.symlinks = true in the webpack config inside of the next.config.js
  3. Manipulating externals requested from the library to be requested from the library/node_modules (for the server-side build to resolve modules correctly)
  4. Commenting out the line https://github.com/vercel/next.js/blob/f98e38c9b634b85e6679e7b5f953a9d98074cfc3/packages/next/build/webpack-config.ts#L601

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…

I experimented a similar issue in _app.js with a catchall page in Next 10

image

Folks, simple fix, remove your global version of react, next and react-dom by doing:

npm remove -g react next react-dom

I’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 react and react-dom one 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.

@jcpsimmons What error do you get?

I think what you actually need is something like this:

config.resolve.alias['react'] = path.resolve(__dirname, '.', 'node_modules', 'react');
config.resolve.alias['react-dom'] = path.resolve(__dirname, '.', 'node_modules', 'react-dom');

I can confirm the same experience as @wasd171 in a Rush + PNPM monorepo. I’ll just use ~9.4.4 in 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.json

{
  "dependencies": {
    "next": "9.5.1",
    "myUILibrary": "git+ssh://git@github.com/MyRepo/library-web-ui.git#master",
    "react": "16.13.1",
    "react-dom": "16.13.1"
  }
}

and I yarn link myUILibrary to my locally checkout MyRepo/library-web-ui which also has react installed.

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-dom

If you are using next-transpile-modules and 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-react

If 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_modules folder inside your library (at least if you ever ran npm i or npm link in that library folder).

When react gets resolved from this library folder it will resolve to the one in that node_modules folder and you get dual copies of react causing the problem. If I delete the node_modules folder inside my lib or install it using something else than npm link then 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 until v9.0.6-canary.4 and 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/8739

My component library uses react, react-dom, and styled-components. The configuration for this is as follows

  • Added the packages as devDependencies and included them in peerDependencies
  • Added the packages as externals in my webpack config
  • Added resolve aliases to these packages in my next config
  • Transpiled the component library module with next-transpile-modules

Update

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

if (isServer) {
  config.externals = [
    'react',
    'react-dom',
    'styled-components',
    ...config.externals
  ]
}

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 react being bundled in the server chunks. And that’s why we get the Invalid hook call error on the server.

I was able to resolve this just now in the repro by moving the react and react-dom dependencies 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?

@jcpsimmons What error do you get?

I think what you actually need is something like this:

config.resolve.alias['react'] = path.resolve(__dirname, '.', 'node_modules', 'react');
config.resolve.alias['react-dom'] = path.resolve(__dirname, '.', 'node_modules', 'react-dom');

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()); }

window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);

}, []);

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 running next dev in 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 peerDependencies instead of regular dependencies because it was downloading multiple instances of it. So if you’re having the invalid hooks error, try these steps:

  1. Include your third party module as a dependency in your main project.
  2. Run a npm install to get all your modules installed.
  3. Open your terminal/console and navigate to the module, then run sudo npm link.
  4. Navigate back to your main project and run a 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.
  5. Run your 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 npm to yarn. 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 withRouter but then the same error is thrown on the wrapped component instead.

import { useRouter } from 'next/router'

function withPrivateRoute(WrappedComponent) {
const router = useRouter();                    //**** ERROR IS THROWN HERE *******
class WPR extends React.Component {
    componentDidMount(){
        console.log('wrappeed', WrappedComponent);
        // const { router } = this.props;
        const intendedRoute = router.pathname;
        // const isAdmin = !!cookies.get('isAdmin');
        // const isAuthenticated = !!cookies.get('username');
        const isAuthenticated = false;
        const isAdmin = false;
        if (!isAuthenticated) {
            router.push({
                pathname: '/login',
                query: { from: intendedRoute },
            });
        }
        if (
            isAuthenticated &&
            router.pathname.includes('admin') &&
            !isAdmin
        ) {
            router.push('/');
        }
    }

    render() {
        return ({ ...props }) => <WrappedComponent {...props} />;
    }
}
return WPR;
 }

  export default withPrivateRoute;

Strangely, using resolve.alias does not seem to affect packages outside the project root.

Here’s my next.config.js file:

const path = require('path')

module.exports = {
  webpack: config => {
    const { alias } = config.resolve || {}
    alias.react$ = path.resolve('node_modules/react')
    alias['react-dom$'] = path.resolve('node_modules/react-dom')

    config.resolve = {
      ...config.resolve,
      alias,
    }

    return config
  }
}

I’m using yarn link with a local package that exists in a Lerna monorepo. Its node_modules does not contain a copy of react, but the monorepo root does. I wouldn’t expect that to make a difference as long as resolve.alias is used, but that’s unfortunately not the case. After removing the copy of react from the monorepo root, I’m now getting a Cannot find module 'react' error instead.

I think that I’ve found the issue!!! I think that it is a combination of 2 things:

  1. usage of sym-link for node_modules
  2. i18next / react-i18next were not external in server bundles!! image In my case, when it explodes on production build, it complains on i18next useTranslation hook…

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/, as i18next & react-i18next does!!

So, if you change this:

res.match(/next[/\\]dist[/\\]/) 

into

res.match(/[/\\]next[/\\]dist[/\\]/) 

The server bundle will exclude all libs that are not next & ends with next/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_module packages will cause this (with dependencies on react(-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 react into our projects’ node_modules folder. In our case it was related to storybook (yarn why react helped a lot 😄). We were planning to move storybook to a separate project anyway so I think this solution will work in our case.