Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

Difference is that counter + 1 is only an operation and counter++ is an operation with an assignment. In React you shouldn't assign your state directly but use the setter method. So in your case it is better to use counter + 1

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!