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

142
Visualizações
Why should we use setState when we modify some values in React?

I'm very beginner at React. And now I'm studying about setState() method.

I'm studying with an instruction of tutorial for beginners, but there's something i can't understand.

The topic that the tutorial dealt was making Counter component that displays changing value when we click plus or minus buttons.

The example was like :

function Counter() {
  const [number, setNumber] = useState(0);

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

  const onDecrease = () => {
    setNumber(number - 1);
  }

  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}   

And while the learning, i thought this method :

function Counter() {
    let number = 0;
    
    const onIncrease = () => {
        console.log({number});
        number++;
        console.log({number});
    }
    const onDecrease = () => {
        number-=1;
    }
    
    return (
        <div>
            <h1>{number}</h1>
            <button onClick={onIncrease}>+1</button>
            <button onClick={onDecrease}>-1</button>
        </div>
    )
}

As you may easily recognize, it didn't work.

But I can't understand why it doesn't work properly. It seems to related with why we use setState() as I think.

Thank you for your concern, and I would really appreciate it if you could leave a reply.

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

0

This all ties into the React lifecycle. When you have an MV* library, the idea is that there is a data model wired to a UI, and when you update your data model the library will do the work to update your UI accordingly. In order for the library to update the UI, it critically must know that the data model has changed. If you simply update the values in plain JS, the library has no easy or performant way of knowing that the data model has changed. For this reason, the library provides its own methods for updating the data model-- if you only update the data model with these methods, then the library will know that they data model has changed and that a update to the UI must be scheduled.

about 4 years ago · Juan Pablo Isaza Relatório

0

Reassigning a variable, by itself, (almost) never has any side effects - this is true not only in React, but in all JavaScript as well. You need to tell React in a way that it understands that a value has changed and that the component needs to re-render as a result - thus the need for a function call (setNumber).

With React's paradigm, the way a component renders should be determinable completely from that component's state (and props), for the most part. React can keep track of changes to state and props easily - it can't (nothing in JavaScript can) keep track of reassigned variables automatically.

Calling a state setter like setNumber tells React to:

  1. Update React's internal state data for this component
  2. Re-render the component

If you just reassign a variable, like number++, neither of those can be accomplished.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can imagine like this

Reactjs function component is also a normal function, every renders the function get invoked all over again.

And when you declare let number = 0; as a local variable in a normal function, does it keep the last value from the last invoke? Obviously not,

Then React works the same way.


So, In order to persist your local variable within invokes, you will need to have a way to store them outside of your function, useState or useRef are two of them.

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