Ian Warburton
Ian Warburton

Reputation: 15676

Error when using useState in official example

This code came from here.

import React from 'react';
import useState from 'react'

let f = function() {

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

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

export default f;

Firstly, this line from that page...

import React, { useState } from 'react';

... results in useState being null, but I changed that line. Anyhow, I get the following error...

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

This error goes way if I change the code to this...

const [count, setCount] = [1, () => {}]

So I figure useState is the problem - it's not a function. Perhaps my custom import is not doing the correct thing. In which case, why doesn't the official import work?

I'm using React 16.8.1. My packages file has these...

"react-dom": "16.8.1",
"react": "16.8.1",

I've delete the local node_modules folder and run npm install --force -g.

Console.log on useState gives...

enter image description here

Upvotes: 1

Views: 5496

Answers (2)

Ian Warburton
Ian Warburton

Reputation: 15676

You have to restart the web server to recompile with a new version of React. Doh.

Upvotes: 1

Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6289

useState is a named export. You cannot import it like a default export.

Change these two lines

import React from 'react';
import useState from 'react';

to

import React, { useState } from 'react';

Upvotes: 3

Related Questions