0

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

Simmi George
  • 145
  • 1
  • 3
  • 12

1 Answers1

2

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

Bas
  • 1,353
  • 3
  • 7
  • 18