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:
Asked
Active
Viewed 53 times
0
-
1setState is async method, you are printing the value just after the setting. Click it one more time and you should see the value as expected. – Fazwelington May 03 '22 at 23:27
-
First time is empty , additional clicks are ok – mercury May 03 '22 at 23:44
1 Answers
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')

Bas
- 1,353
- 3
- 7
- 18