React 16.7 TypeError: (0 , _react.useState) is not a function

Viewed 9778

Error:

  TypeError: (0 , _react.useState) is not a function

My current react versions:

   "react": "^16.7",
   "react-dom": "^16.7",

src/App.js:

  import {memo, useState} from 'react'
  export default memo(() => {
     useState(false)
     return 'OK'
  })

src/App.test.js:

   import React from 'react'
   import App from './App'
   import renderer from 'react-test-renderer'
   it('renders without crashing', () => {
        const tree = renderer.create(<App />).toJSON()
        expect(tree).toMatchSnapshot()
   })

How to resolve this issue?

2 Answers

The root cause is that the react V16.7 does not have hooks

Resolution is to downgrade to

   npm i react@next react-dom@next 

which as of 2018/12/20 is 16.7.0-alpha.2:

    yarn add react@next react-dom@next

then lose the test renderer:

 import React from 'react'
 import ReactDOM from 'react-dom'
 import App from './App'
 it('renders without crashing', () => {
    const div = document.createElement('div')
    ReactDOM.render(<App />, div)
    ReactDOM.unmountComponentAtNode(div)
 })

This is what package.json should have:

  "react": "^16.7.0-alpha.2",
  "react-dom": "^16.7.0-alpha.2",

In my case, the mistake was in the imports. My IDE imported the useState hook from import 'react/cjs/react.development' and it dosen't work on production.

Related