Launching Next.js with Styled Components throws React Hooks error
See original GitHub issueBug report
Describe the bug
When using Next.js and Styled Components and launching Next.js from Keystone, an erroris printed to the stdout:
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:
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
I’ve isolated this specifically to launching Next.js from Keystone’s dev
command, as navigating to the Next.js directory and launching from there doesn’t produce an error.
I further tracked the cause of the error to being the 3rd point in the error message: “You might have more than one copy of React in the same app”. Following the stack trace, I’ve found Next.js is using Keystone’s version of React.
This is the good news - moving React and ReactDOM to Next’s peerDependencies
in package.json
resolves the issue. This is probably a documentation change IF the maintainers deem this necessary to document in the first place (it’s a pretty niche use case). If that is the case, I’d be happy to raise a pull request (with some guidance).
To Reproduce
- Install Next.js in a subdirectory
- Install and configure
@keystonejs/app-next
- Install and configure Styled Components following this example https://github.com/zeit/next.js/tree/canary/examples/with-styled-components (Note, most of the implementation is in
pages/_document.js
andpages/_app.js
. - Run
yarn dev
- Observe the error in the stdout or visit the app in a browser
Expected behaviour
Keystone should successfully boot a Next.js app with Styled Components without producing errors.
System information
- OS: macOS
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
I just followed the “Getting Started” guide for setting up a new keystone app, and after using the
app-next
package with a vanilla Next.js repo, I’m getting the same error:I’m guessing this is caused by mismatching versions of React between Next.js and Keystone’s Admin UI. What is the correct fix for this?
EDIT I fixed this by moving my
next
dependency to the rootpackage.json
, deleting thepackage.json
andnode_modules
folder in the next app, and running a cleannpm i
. This means that Next and Keystone will share the same React version (based on the one in the keystone admin UI dependency).Aaaaand accidentally hit “Close and comment”. Whoops!