next.js: Invalid hook call. Hooks can only be called inside of the body of a function component.

Bug report

Describe the bug

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://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

To Reproduce

Details So the error points on this code

static async getInitialProps (ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage
    const {
      req: { locale, localeDataScript }
    } = ctx
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        userAgent: ctx.req.headers['user-agent'],
        helmet: Helmet.renderStatic(),
        locale,
        localeDataScript,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }

Screenshots

Screen Shot 2019-06-21 at 12 10 08 PM

Additional context

I suspect that it treats the ctx.renderPage = () => as a react hooks.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 14
  • Comments: 24 (7 by maintainers)

Most upvoted comments

For those who are still encountering this error after troubleshooting all the proposed fixes, double-check that you are using the correct directory casing when running your project. I continued to have problems on my PC and discovered this was the reason why.

https://stackoverflow.com/questions/58365151/hooks-error-invalid-hook-call-using-nextjs-or-reactjs-on-windows

I had a node_modules folder in a parent directory up the tree that was causing issues. I deleted that and it started working as expected,

This happens to me sometimes when I update dependencies or run npm install without clearing out old node_modules or the build folder (dist).

First, make sure all dependencies are up-to-date in your package.json file, specifically react and any related react-releated dependencies like react-dom. Also, it may be that you have other dependencies that need certain versions of react. Make sure things match - usually for me, this just means the latest available version.

Then, I delete node_modudes, dist/ and package-lock.json, and re-run npm install and restart the app (which rebuilds the /dist folder. Seems to always fix it. Never comes back for me after that until the next time I edit the package.json file.

I’m grappling with this one too. I don’t use styled-components. I tried deleting node_modules etc. without luck. I tried adding aliases and resolves for react in my next.config.js file and package.json without luck. I’m using react 16.8.6, react-dom 16.8.6, and next 9.0.4. npm ls says there’s only one of each. The app uses material-ui. I am not using any npm links.

Repository: https://github.com/dancancro/questions/tree/invalid-hook-call

Codesandbox: https://codesandbox.io/s/github/dancancro/questions/tree/invalid-hook-call/?fontsize=14

Stackoverflow: https://stackoverflow.com/questions/57647040/nextjs-invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-fun

The error is here: https://gist.github.com/dancancro/2dfafb053aaaedfade406fd4f67eb68a render -> renderToString -> ReactDOMServerRenderer.read -> ReactDOMServerRenderer.render -> Object.WithStyles [as render] …

The offending hook is on line 17428 of this file in a withStyles function. Search for “var classes = useStyles(props)”. The problem is with next-generated code. The code I wrote doesn’t use withStyles or any hooks. https://raw.githubusercontent.com/dancancro/questions/invalid-hook-call/.next/static/development/pages/index.js

UPDATE: removing this from my next.config.js solved the problem:


	webpack: config => {
		config.externals = [
			'/'
		]
		return config
	},

I’m experiencing this as well, after updating a bunch of dependencies. Difficult to pinpoint the cause. FWIW I did clear out node_modules and package-lock.json, and it did not solve the issue.

My stack trace pointed to the following line as the source of the error:

  3 | export default class DefaultDocument extends Document {
  4 |   static async getInitialProps (ctx) {
> 5 |     return await Document.getInitialProps(ctx);
  6 |   }

This seems like pretty standard boilerplate for Next, unless I’m missing something that changed in one of the recent major versions?

Somewhat related to @dbeaudway’s comment, it’s possible to get this error when running the project from a symlinked folder. For example, if the real path to your project is C:/Projects/my-app but you have a symlink to the Projects folder, say at C:/Users/UserName/Projects. Running the project from C:/Users/UserName/Projects/my-app won’t work.

I got the problem because I used Powershell. I try to use command prompt and the problem does not happen any more. Anyone can explain me what happens when I use Powershell.

what version using styled-components? because i have same problem, but only version 5 beta broken currently