I have an error about invalid useState hook in this case?

Viewed 29

i have a component like that. I also use useState hook in that component and my react project in version 17.0.2. But in the console dev tool apparent "Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function " .Can u help me, pls

import { useState } from 'react'
 
 
function AddProduct () {

  const [product , setProduct] = useState(1)
  const handleChange = (e) => {
    setProduct(e.target.value)
  }
   return (
       <div>
       <input value={product} onChange={handleChange}/>
       <button>Save</button>
       </div>
   )
}
export default AddProduct
1 Answers

One of the blow reasons can be the problem:

  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 think it might be the first reason and you haven't mentioned the version of the 'react-dom' you are using. As an example below code should work since It has compatible react and react-dom versions and they both support function component and hooks:

"dependencies": {
    "react": "17.0.1",
    "react-dom": "17.0.1"
  },

App.js

import * as React from "react";
import { useState } from "react";
import { render } from "react-dom";

function App () {

  const [product , setProduct] = useState(100)
  const handleChange = (e) => {
    setProduct(e.target.value)
  }
   return (
       <div>
       <input value={product} onChange={handleChange}/>
       <button>Save</button>
       </div>
   )
}
export default App;

render(<App />, document.getElementById("root"));
Related