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

310
Visualizações
My React Simple counter doesn't work as expected

I starting to learn React and I was wondering why my Counter it's not working :( My objective is: When you press the button, Counter function start to "count" and render "count" state in the td. I don't know what I'm doing wrong.

import React, { useState } from "react";


function Clock() {
  const customStyle = {
    fontSize: "100px"
  };
  const tdStyle = "px-3 border border-dark border-3 rounded bg-secondary";
  //-------------------------------------------------------------------------
// THIS FUNCTION 
  const [count, setCount] = useState(0);

  function Counter(){
    setCount(count + 1)
    setInterval(Counter, 1000)
  }  
 

  return (
    <div className="rounded border border-dark border-3">
      <table>
        <tr style={customStyle}>
          <td className={tdStyle}>
            <i className="fa-solid fa-clock"></i>
          </td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>{count}</td>    //here is showed
        </tr>
      </table>
      <button onClick={Counter}>Pulsar</button>    //button
    </div>
  );
}

export default Clock;

This works with real seconds

function Counter(){
    setCount(new Date().getSeconds())
    setInterval(Counter, 1000)
  }

But it is not what I want. I want a simple counter.

In addition, How could I use "onLoad" event in this code? for when page is loaded It start counting and rendering it in the page?

Thank you in advance!!

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

0

Firstly, you need to put your setInterval in a useEffect hook because you are currently creating a new interval every time your state updates (i.e every second), which will drastically slow down your app. Secondly, you should use the useEffect cleanup function to remove the interval each time your component re-renders to prevent duplicate interval creation. Finally, given your state depends on a previous state snapshot (i.e the previous count value), you should update your state using a callback (to ensure you access the most recent state snapshot)

useEffect(() => {

  function counter(){
    setCount(prevState => prevState + 1)
  }

  let countInterval = setInterval(counter, 1000)

  return () => clearInterval(countInterval)

}, [])

Given you are calling the useEffect every time the count updates, you could (and probably should) use setTimeout instead of setInterval. In that case, you wouldn't require the cleanup function.

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand how useState works correctly I believe you're running into some asynchronous issues with your count state, which would explain why your "real seconds" example works.

I would suggest moving your setInterval() function to a useEffect hook. The useEffect hook would also be the answer to your onLoad question as well.

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


function Clock() {
  const customStyle = {
    fontSize: "100px"
  };
  const tdStyle = "px-3 border border-dark border-3 rounded bg-secondary";
  //-------------------------------------------------------------------------
// THIS FUNCTION 
  const [count, setCount] = useState(0);

useEffect(() => {
  setInterval(counter, 1000);
}, []);

  function Counter(){
    setCount(count + 1)
  }  
 

  return (
    <div className="rounded border border-dark border-3">
      <table>
        <tr style={customStyle}>
          <td className={tdStyle}>
            <i className="fa-solid fa-clock"></i>
          </td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>0</td>
          <td className={tdStyle}>{count}</td>    //here is showed
        </tr>
      </table>
      <button onClick={Counter}>Pulsar</button>    //button
    </div>
  );
}

export default Clock;

I'm not 100% positive this will work as expected as I'm unable to test it at this moment, but I believe this is what it you're looking for. Here is documentation on useEffect as well, https://reactjs.org/docs/hooks-effect.html

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