Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs TypeError: Object(...) is not a function when using hooks

I am trying to export a normal functional component using the react hooks but I am getting this error.

TypeError: Object(...) is not a function

when I remove the hooks and export it without any states it works. Exporting the same code as a Class component also works.

import React,{ useState } from 'react';

const  Mycomponent = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Mycomponent;

here is how I am importing and using functional component.

import Mycomponent from './mycomponet';
class MYClassComponent extends Component {
  render() {
    return (
      <Mycomponent />
    }
}

I am using react 16.6.3 and used create-react-app.

like image 859
saurabh Avatar asked Jan 01 '23 22:01

saurabh


1 Answers

I am using react 16.6.3...

That's the problem. Hooks were added in v16.8, so useState in your code is undefined.

(This is one of those times that transpiling hid the error from you [not that you have much choice if you need to support older environments]. If that had been a native import statement, it would have failed with a useful error saying that React didn't have a useState named export. But when using a CJS or AMD version of React, your code gets converted to something doing var useState = React.useState; and so it doesn't error out, it just gives you undefined — which isn't a function. :-) )

like image 82
T.J. Crowder Avatar answered Jan 08 '23 02:01

T.J. Crowder