Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda