Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid hook call in 9.0.6 #9022

Closed
baldurh opened this issue Oct 10, 2019 · 99 comments · Fixed by #9956
Closed

Invalid hook call in 9.0.6 #9022

baldurh opened this issue Oct 10, 2019 · 99 comments · Fixed by #9956
Assignees
Labels
Webpack Related to Webpack with Next.js.

Comments

@baldurh
Copy link

baldurh commented Oct 10, 2019

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 🙂

@lfades
Copy link
Member

lfades commented Oct 10, 2019

@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

@baldurh
Copy link
Author

baldurh commented Oct 10, 2019

@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.

@isaachinman
Copy link
Contributor

@baldurh Just ran into this with next-i18next as we've got nested NextJs apps as examples. Did you find a workaround?

@baldurh
Copy link
Author

baldurh commented Oct 22, 2019

@isaachinman We have not. We haven’t managed to upgrade to 9.x yet because of other reasons so I haven’t been looking into it. Does anyone have an idea of where the code affecting this might be? I’d love to understand the problem better.

@isaachinman
Copy link
Contributor

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.

@jaredcwhite
Copy link

I had a similar error come up recently and had to downgrade to 9.0.5 (and React 16.8.x). I sort of narrowed down the problem I saw to Next's use of MDX, but I don't have any concrete details beyond that.

@felixmosh
Copy link
Contributor

felixmosh commented Nov 3, 2019

I've dug into the same issue with a pretty big project based on Next & next-i18next.

I saw that this error can be thrown by 3 reasons:

  1. Misaligned react & react-dom versions - not applied to my app
  2. 2 versions of react-dom imported - not applied to my app
  3. Improper use of React hooks - I don't use hooks but some libs are, and it looks like it works for every one else.

The strange thing is that it happens only on production build.

@baldurh
Copy link
Author

baldurh commented Nov 6, 2019

@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.

@Timer
Copy link
Member

Timer commented Nov 9, 2019

It seems you aliased react but not react-dom. Can you try that?

@baldurh
Copy link
Author

baldurh commented Nov 9, 2019

@Timer Thanks. I tried but it did not have any effect

@Timer Timer added this to the 9.1.4 milestone Nov 9, 2019
@baldurh
Copy link
Author

baldurh commented Nov 9, 2019

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
Copy link
Author

baldurh commented Nov 9, 2019

@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.

@Timer
Copy link
Member

Timer commented Nov 9, 2019

Ah, yes. Improperly published node_module packages will cause this (with dependencies on react(-dom|) instead of peer dependency).

@felixmosh
Copy link
Contributor

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?

Can you elaborate regarding the changes that you have done in this repo?

I run npm ls react or npm ls react-dom I got only my next app in the list.

@baldurh
Copy link
Author

baldurh commented Nov 10, 2019

@felixmosh Sorry, apparently the push failed for me yesterday. Now the changes are definitely there 😅 I moved react and react-dom from the app folder into the root folder so now you need to do yarn/npm install in both the app folder and the root folder before you run the app. Hope this is clear enough.

We’re going to have to do some changes to our build system to get this working in production so this solution is still a bit of a hassle for us 😝

@felixmosh
Copy link
Contributor

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

@baldurh
Copy link
Author

baldurh commented Nov 10, 2019

@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 😇🙏🏻

@bryan
Copy link

bryan commented Nov 29, 2019

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 facebook/react#13991 and facebook/react#15315 (comment) for reference as I found those links before this issue.

@creativej
Copy link

Hi any update on this issue? We have a monorepo and we are encountering this exact issue.

@Timer Timer modified the milestones: 9.1.5, 9.1.6 Dec 10, 2019
@nodkz
Copy link

nodkz commented Dec 12, 2019

Meet with the same problem.
v9.0.5 works great with hooks for components imported outside the rootFolder.

Starting from 9.0.6 till 9.1.6-canary.5 have the same problems.

The problem occurs only on the server-side. If SSR disabled (eg. load external component via dynamic) then all works as expected for versions >=9.0.6.

@felixmosh
Copy link
Contributor

@nodkz it is an issue with react package resolving, therefore it happens only in node.

@ijjk ijjk removed this from the 9.1.6 milestone Dec 17, 2019
@jeremiedubuis
Copy link

Also having issue on next.js 10.0.5, had to add npm-force-resolutions and force resolutions to solve it.

@justincy
Copy link
Contributor

justincy commented Apr 7, 2021

Also having issue on next.js 10.0.5, had to add npm-force-resolutions and force resolutions to solve it.

@jeremiedubuis Could you share what that looks like? I've never been able to get it to work reliably with next.js

@lucasvst
Copy link

lucasvst commented Apr 9, 2021

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

@belakm
Copy link

belakm commented Apr 14, 2021

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

This works for us as well but it breaks styled-components on SSR 😞

@DundieWinner
Copy link

I recently erroneously removed react and react-dom from peerDependencies of a library my Next app consumes. This resulted in the error described herein for some reason. Adding those items back in the library and then upgrading the version inside my Next project made this error go away.

So my takeaway is: If you control one or more of the libraries in your project, make sure to include react and react-dom in peerDependencies.

@ChocolateLoverRaj
Copy link

@JaredMichel Now even with react in peerDependencies, npm 7 will install it in local development.

@timneutkens timneutkens assigned ijjk and unassigned Timer Jun 22, 2021
@mrcMesen
Copy link

mrcMesen commented Aug 3, 2021

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.

This works to me.

@kodunmi
Copy link

kodunmi commented Nov 2, 2021

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

@belakm
Copy link

belakm commented Nov 2, 2021

@kodunmi Try checking for window if you are using SSR.

Wrap window dependant code in an if block like this:

if (typeof window !== 'undefined') {
  // your window dependant code
}

Window is undefined on server side.

@kodunmi
Copy link

kodunmi commented Nov 2, 2021

I'm checking it on the getWindowDimensions function

That's not the issue

function getWindowDimensions() {
if (typeof window !== "undefined") {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}

return null

}

@belakm
Copy link

belakm commented Nov 2, 2021

@kodunmi You are adding an event listener for "resize" on window object later on in your hook's useEffect hook. You should also move handleResize() function definition outside the hook.

export function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize); // <---- you are calling window here
    return () => window.removeEventListener('resize', handleResize); // <---- and here
  }, []);

  return {
    windowDimensions,
  };
}

@kodunmi
Copy link

kodunmi commented Nov 2, 2021

Okay I will restructure the code

But my problem is not that code

My problem is using hook in custom hook is throwing error

`export function useWindowDimensions() {
const [counter, setCounter] = useState(0)

return counter
}`

the above still throws Error: Invalid hook call.

@styfle styfle modified the milestones: 11.1.x, 12.0.4 Nov 5, 2021
@timneutkens timneutkens removed this from the 12.0.5 milestone Nov 17, 2021
@timneutkens timneutkens added Webpack Related to Webpack with Next.js. and removed point: 3 labels Nov 18, 2021
@maxy4u
Copy link

maxy4u commented Dec 1, 2021

@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

@sunb0002
Copy link

sunb0002 commented Mar 7, 2022

I'm still facing this issue today. Straight-away
npx create-next-app blog-app
npm run dev
will end up with Error: Invalid hook call.

The latest dependencies are:
"dependencies": {
"next": "12.1.0",
"react": "17.0.2",
"react-dom": "17.0.2"
}

@balazsorban44
Copy link
Member

You are likely having a project setup issue, maybe a symlink or a global install on react. I'm closing this, as I am unable to reproduce this with a clean project. If anyone has a similar issue, it's likely this should be opened in the Discussions instead.

@github-actions
Copy link
Contributor

github-actions bot commented Apr 6, 2022

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 6, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Webpack Related to Webpack with Next.js.
Projects
None yet
Development

Successfully merging a pull request may close this issue.