React component with hooks as npm module
Asked Answered
G

2

6

When I try to use React Hooks in module which I use as dependency it's fail. I'm getting a following 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:

But if I use class-based component, it's ok. Why can this happen?

Here is excerpt from my package.json

{
  "main": "dist/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "./node_modules/.bin/babel src -d dist",
    "prepublish": "npm run build"
  },
  "peerDependencies": {
    "react": "^16.10.2",
    "react-router-dom": "^5.1.2"
  },
  "devDependencies": {
    "axios": "^0.19.0",
    "jwt-decode": "^2.2.0",
    "qs": "^6.9.0",
    "@babel/cli": "^7.6.4",
    "@babel/core": "^7.6.4",
    "@babel/preset-env": "^7.6.3",
    "@babel/preset-react": "^7.6.3"
  }
}

Here is the component:

const Test = () => {
  const [state, setState] = React.useState('test')
  return <div>{state}</div>
}
Govan answered 11/10, 2019 at 14:17 Comment(5)
it looks ok, can you share more code? like the way you import Test and use it in the different components. BTW you can't use hooks in a class componentPelagianism
I have the same issue - but when using hook in the function component which is in subfolder of consumer app, there is no problem, but when exported to npm, consumer fails. Maybe it's related to module system or target version? I tried es5 and es2017 both same error.Scyphus
Are you using webpack? In that case what helped me was to set alias to react. There were really more react instances loaded as error states.Scyphus
Jozef, should I set alias in the project or in the module I'm linking?Inbreed
Did you solve this problem? @GovanFrostbitten
E
1

Maybe what you are trying to use is useState and not useEffect:

const Test = () => {
  const [state, setState] = React.useState('test')
  return (<div>{state}</div>)
 }
Efik answered 11/10, 2019 at 14:22 Comment(3)
Sorry, yes it’s my typo, but it doesn’t change anything, the result is the sameGovan
Could you please share the part of code where Test is rendered?Efik
Just simple export default and import Test from 'npm-package-name'.Govan
P
0

You Cant Create A npm library with hooks you need to convert your function into class component and can be made as a library

Polarization answered 1/12, 2020 at 23:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.