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

156
Visualizações
React render component even though state doesnt change
import { useState } from "react";

export default function App() {
  console.log("rendered...")
  const [count, setCount] = useState(0);

  const increaseCount = () => {
    setCount(count + 1);
  };

  const setFourValue = () => {
    setCount(4);
  };
  return (
    <div className="App">
      <div
        style={{ display: "flex", alignItems: "center", columnGap: ".25rem" }}
      >
        <button onClick={increaseCount}>Increase</button>
        <button onClick={setFourValue}>Set 4</button>
        <span>{count}</span>
      </div>
    </div>
  );
}

I try to figure out when and how component render. Situation that i try to is i increased count to 4 and now my count value is 4. But i click to 'Set 4' button my count value is still 4 but still component re-rendered. After that if click again 'Set 4' button component doesn't re-render. Why ?

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

0

To add on to Barry's answer, when you set the count to4 the first time with setFourValue after increasing it to 4 with increaseCount, it actually isn't 4. Console log the count and you'll see that it's actually 3 even though it displays 4 on the screen.

about 4 years ago · Juan Pablo Isaza Relatório

0

In React, components will only re-render if a state or prop in the component change.

Setting 4 to 4 is not a change.

React is smart enough to not re-render unnecessarily.

about 4 years ago · Juan Pablo Isaza Relatório

0

There's a problem with your increaseCount function. When you are updating a state property using its previous value, the callback argument must be used. This is due to the asynchronous nature of state updates. (See https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)

const increaseCount = () => {
    setCount((count) => (count + 1));
};

It could probably be the reason why the count was 3 instead of 4 as said by @Tim van Dam.

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