useState hooks show the previous value, Please help to find the current value in react js [duplicate]


I am new one in react JS, I am trying to useState to check conunter, its showing the correct value at render, but showing the previous value when i printing in console.

Here is my simple code.

    const [counter, setCounter] = useState(0);

    const incrementCounter = () => {
      setCounter(counter => counter + 1);
    
      console.log("counter " + counter) // this is showing the old value instead of new counter

    }
 
   const decrementCounter = () => {
      setCounter(counter => counter - 1);
 
      console.log("counter " + counter) //// this is showing the old value instead of new counter
    }
   

    return (
        <div>

            <h1>Counter state: {counter}</h1>
            <button onClick={() => incrementCounter()}>+</button>
            <button onClick={() => decrementCounter()}>-</button>
        </div>
)

Thanks in advance…

Source: JavaSript – Stack Overflow

November 8, 2021
Category : News
Tags: DOM | javascript | onclick | reactjs | use-state

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.