简体   繁体   中英

how to use state in same useEffect hook?

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()

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM