ineedhelp
ineedhelp

Reputation: 11

React useState not setting initialValue

useState doesn't seem to be able to set an initial value properly.

I have a component that starts something like this:

import { useState } from 'react';

const App = () => {

  const { currentUser, setCurrentUser } = useState("abc")

  console.log(currentUser)

  return(
    <div>{currentUser}</div>
  )
};

However, it keeps logging "undefined" no matter what value I set as the initial state.

Similarly, whenever I try to call setCurrentUser, I get a TypeError that "setCurrentUser" is not a function.

Can anyone help diagnose this issue?

Upvotes: 1

Views: 43

Answers (1)

acdcjunior
acdcjunior

Reputation: 135752

The correct syntax is:

const [ currentUser, setCurrentUser ] = useState("ABC")

not

const { currentUser, setCurrentUser } = useState("ABC") // wrong syntax, see above

See the new docs on useState for a better, direct, explanation.

Upvotes: 4

Related Questions