5

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.

3
  • What bundler and bundler settings are you using? What does the compiled/transpiled code look like? Have you verified that useState is in fact a function? What version (and distribution file) of React are you using? Commented Jun 7, 2019 at 13:14
  • I am using react 16.6 and used creat-react-app
    – saurabh
    Commented Jun 7, 2019 at 13:15
  • @saurabh - React hooks are available from v16.8 onwards.
    – Tomer
    Commented Jun 7, 2019 at 13:19

1 Answer 1

10

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. :-) )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.