Using useState reacthook in a reactjs module is throwing error: Invalid hook call

51 views Asked by At

I am trying to create a reactjs module, develope and maintain separately from the main reactjs app I am working on.

import React, { useState } from 'react';

function MyComponent(props) {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>This is a basic React component.</p>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default MyComponent; 

The build configurations look pretty much like this: https://github.com/iamsmkr/react-module-starter and the module is being used as per README.

Usage in the App.js:

import MyComponent from 'react-module-starter';

function App() {
  return (
    <MyComponent></MyComponent>
  );
}

export default App;

App package.json looks like (Note that the app was generated by create-react-app):

{
  "name": "test-react-seesaw",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Trying to use useState hook is throwing error:

Uncaught 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.
    at resolveDispatcher (react.development.js:1476:1)
    at useState (react.development.js:1507:1)
    at l (index.js:4:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)

I'm not sure if there is anything wrong with my build configuration or something? This is the first time I am trying to develop reactjs module and utilize in apps. Please suggest.

0

There are 0 answers