Reading component state just after setting when using useState hook in react

Asi*_*K T 0 reactjs react-hooks

This console.log is not working: It'll just print the previous state value as set is async.

const SomeCompo = () => {
  const [count, set] = useState(0);
  const setFun = () => {
    console.log(count);
    set(count + 1);
    console.log(count);    
  }
  return <button onClick={setFun}>count: {count}</button>
}
Run Code Online (Sandbox Code Playgroud)

I had to read the count in the render itself:

const SomeCompo = () => {
  const [count, set] = useState(0);
  console.log(count);
  const setFun = () => {
    set(count + 1);
  }
  return <button onClick={setFun}>count: {count}</button>
}
Run Code Online (Sandbox Code Playgroud)

Is there a better way to read the value as I don't want to console for every render.

rav*_*l91 5

你可以用useEffect这个

useEffect(() => {
   console.log(count);
}, [count]) //[count] is a dependency array, useEffect will run only when count changes.
Run Code Online (Sandbox Code Playgroud)