-1

After setting the state of a variable in useEffect, I console.log it on the next line which gives undefined

Why is this so and how do i use the state variable?

const [item, setItem] = useState();

    useEffect(() => {
      const doFunction = async () => {
        try{
          setItem("hi")
          console.log(item)
      },[item]);
    doFunction()

skyboyer
  • 22,209
  • 7
  • 57
  • 64
timmy123
  • 13
  • 4
  • Does this answer your question? [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – ggorlen Mar 18 '21 at 17:29
  • Welcome to SO! `setState` is asynchronous, so your `console.log` below the `setState` will execute first. `setState` just _registers_ a value for React to use in the next re-render and isn't anything like a synchronous assignment. Please see the canonical dupe. – ggorlen Mar 18 '21 at 17:30
  • Your effect will run into an infinite loop. You're setting `item` in the effect, and you're asking for the effect to get executed whenever `item` changes (the `[item]` array you're passing in). In your effects where you're setting a state, you don't try to also fetch the same state (and you don't need to, since you already have the value). – V Maharajh Mar 18 '21 at 17:30
  • If you setState inside an effect of the same state it will result in infinite loop – Najma Muhammed Mar 18 '21 at 18:02

1 Answers1

1

With hooks it's rather impossible because setState is asynchronus function which means that state of items can't be set immeditiely. You can create another useEffect to handle when state changed.

useEffect( () => {
    setItems( "hi" )
}, [] ) // empty array means "when component mounted"

useEffect( () => {
    if ( items ) {
         /* do something here */
    }
}, [items] ) // array with items means "when itemas state change"

If you realy want to use value which you passing to setState in same hook you can store it for a while in normal variable.

useEffect( () => {
    const temp = "hi"
    setItems(  temp )

    console.log( items ) // undefined
    console.log( temp ) // "hi"
}, [] ) // empty array means "when component mounted"
Kishieel
  • 1,811
  • 2
  • 10
  • 19