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

375
Visualizações
Why doesn't a variable increment in my React component as expected?

I'm a React learner and I want to understand something. The code below doesn't work, it's just a component with two buttons that add or substract a number and display it. Here's the whole code :

import React from "react";
import { useState } from "react";

const Compteur = () => {
  let i = 0;
  const [number, setNumber] = useState(0);

  const increment = () => {
    i++;
    setNumber(i);
  };

  const decrement = () => {
    i--;
    setNumber(i);
  };

  return (
    <div>
      <button type="button" onClick={increment}>
        +
      </button>
      <button type="button" onClick={decrement}>
        -
      </button>
      <p>Number : {number}</p>
    </div>
  );
};

export default Compteur;

But if I replace setNumber(i) by setNumber(number + 1), it works well. What's the problem with this i variable ? Thanks for your help !

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Welcome to React!

The problem in your example is that each time the component rerenders (in your case due to a state change), i is reinitialized and assigned a value of 0. I think you're thinking of the component more as a loop, versus a javascript file. React does a great job as maintaining state, and that state will stay the same though rerenders of the component, which is why it's working as expected when you use number (a piece of React state) instead of i

about 4 years ago · Juan Pablo Isaza Relatório

0

So your problem here is setting let i = 0; as react code is rerun on every rerender, which is caused by state change (among other ways).

So when you call setNumber react then says "okay, rerender the page" and it makes its way down your code, and sees "set i to be 0" and then when you increment the code is saying "i++" or in this case "0 + 1" (because i is set to 0 again).

Essentially, every time react rerenders the component, it's going to reset the value in the variable. That's why we have to use useState because react is then able to keep track of those values.

Your example setNumber(number + 1) is how you should be writing this.

about 4 years ago · Juan Pablo Isaza Relatório

0

You are using the variable i which is getting reinitalized every render, your code should be something like this

const increment = () => {
    setNumber(number + 1);
}

const decrement = () => {
    setNumber(number - 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