Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
}

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>
}

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

like image 531
Asim K T Avatar asked Oct 22 '25 19:10

Asim K T


2 Answers

You can use useEffect for this,

useEffect(() => {
   console.log(count);
}, [count]) //[count] is a dependency array, useEffect will run only when count changes.
like image 183
ravibagul91 Avatar answered Oct 24 '25 09:10

ravibagul91


I would suggest not to use setInterval. I would do something like useEffect. This function will be called each time you do a setState. Just like you had callback after setState. Pass the count state in the array, it will watch only for the count change in the state and console your count.

useEffect(() => {
 console.log(count);
}, [count]);

Also if you dont need to rerender your other components, you might wanan use useMemo and useCallback. https://www.youtube.com/watch?v=-Ls48dd-vJE

Here to more read: https://reactjs.org/docs/hooks-effect.html

like image 45
Subhendu Kundu Avatar answered Oct 24 '25 08:10

Subhendu Kundu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!