Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why variable++ is not working the same way as variable+1

This is one of the most basic things in React but I wonder why counter+1 is working, but in counter++ you must double click to increase the number?

import React, { useState } from "react";
import "./App.css";

function App() {
  const [counter, setCounter] = useState(0);
  const counterHandler = () => {
    setCounter(counter + 1);
  };
  return (
    <div className="App">
      {counter}
      <button onClick={counterHandler}>Increment</button>
    </div>
  );
}

export default App;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let x = 3
let y = x++
//output: x=4 y=3

let x = 3
let y = ++x
//output: x=4 y=4

It’s why you need to double click because you have next logic:

console.log(counter) //0
//triggers click
console.log(counter) //0, useState re-assigned to 0
//triggers click 
console.log(counter) //1, useState re-assigned to 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading