Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
Why the output is different between Class Component and Function Component

There are two different types of components, each modifying the value of num continuously when the button is clicked, why the output of the two components is different.

Class Component

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      num: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    setTimeout(() => {
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      this.setState({
        num: this.state.num + 1
      });
      console.log(this.state.num); // 0, 3, 6...
    }, 0);
  }

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

Function Component

export default function App() {
  const [num, setNum] = useState(0);

  const handleClick = () => {
    setTimeout(() => {
      setNum(num + 1);
      setNum(num + 1);
      setNum(num + 1);
      console.log(num); // 0, 1, 2, 3...
    }, 1000);
  };

  return <button onClick={handleClick}>{num}</button>;
}
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda