Bundled React library throws Invalid hook call error
See original GitHub issueBug report
What is the current behavior?
I get the following React error when trying to use my library built with Webpack
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
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
If the current behavior is a bug, please provide the steps to reproduce.
I’ve created a simple library https://github.com/vasilev-alex/webpack-example which reproduces the above error. As soon, as I import a React hook in my lib I get the above error.
What is the expected behavior?
I can use Webpack to bundle React libraries.
Other relevant information: webpack version: 5.46 Node.js version: v12.22.1 Operating System: macOS Big Sur Additional tools: -
I also posted this comment https://github.com/facebook/react/issues/13991#issuecomment-886656170 in the respecting issue https://github.com/facebook/react/issues/13991, none of the suggested solutions helped me.
P.S. using Rollup for the same library works fine.
Issue Analytics
- State:
- Created 2 years ago
- Comments:17 (9 by maintainers)
Top GitHub Comments
hm, looks like different react versions, give me time I will look at this deeply
You need this due https://github.com/vasilev-alex/webpack-example/blob/main/package.json#L21 and your browsers doesn’t support ECMA modules, when you bundle library you don’t need this, most of developers uses bundlers so
import
s will be bundled, for direct usage ECMA modules should be supports in browser, so I recommend to remove it, if you have app and library in one repo - you can use monorepo or solution from above