Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!