Search code examples
reactjsuse-state

Why is useState not working correctly or am I missing something so Obvious?


I'm new to react and just read documentation on useState. So I started trying it in playground, but looks like It doesn't work. When I tried logging value of temp, it is empty. Example below:

link to playground


Solution

  • Read up on the useEffect hook inorder to print state value. setState is async. If you want to print the new temp value, you will need to use the useEffect hook and put a dependency temp on useEffect. This is so whenever temp changes the useEffect would run a callback.

    For more info: https://reactjs.org/docs/hooks-effect.html

    import React, {useState, useEffect} from 'react';
    
    export function App(props) {
      const [temp, setTemp] = useState('')
    
      const handleClick = () => {
        setTemp('Value changes')
     
      }
    
      useEffect(() => {
        console.log("Temp val is ",temp)
      }, [temp])
    
      return (
        <div className='App'>
          <h1>Hello React.</h1>
          <h2 onClick={()=> handleClick()}>Should set temp after clicking here </h2>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    
    // Log to console
    console.log('Hello console')
    

    https://playcode.io/893227