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

269
Visualizações
Why React Class Component and Function Component output is different in setTimeout?

A class component and a function component, both of which can click on the div to modify the value of num.

export default function App() {
  const [num, setNum] = useState(0);
  const click = () => {
    setTimeout(() => {
      console.log(num, "3000");
    }, 3000);
    setNum(num + 1);
  };

  return <div onClick={click}>click {num}</div>;
}
export default class App extends React.Component {
  state = {
    num: 0
  };

  click = () => {
    setTimeout(() => {
      console.log(this.state.num);
    }, 3000);
    this.setState({ num: this.state.num + 1 });
  };

  render() {
    return <div onClick={this.click}>click {this.state.num}</div>;
  }
}

Why is the output of num different in the above two components after clicking

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

0

In class components, when state is set, when the component updates, the new state will be assigned to the state property of the instance. To oversimplify, doing

this.setState(someNewState);

eventually results in React doing something like

theInstance.state = mergedNewState;

As a result, referencing this.state will result in changes being seen if the state updates, because this.state points to something new..


Functional components are different. Unlike class components, nothing gets (visibly) mutated when using their state. Instead, when you call a state setter, the whole function (component) runs again, and the calls to useState return a new value.

In your code, the

const [num, setNum] = useState(0);

results in a num that the click function closes over.. If there's a click, when the timeout callback runs, it'll still close over the same num that was created before the click handler runs. The component will re-render with a new click function, which has a new num number that it closes over, but the old click function will still be referencing the num from the render in which that old function was created.

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