Search code examples
javascriptreactjsgettime

now.getTime() inside useEffect doesn't work


I wanted to record how many time passed until user click the button. My plan was like: (the time when user enter the page) - (the time when user click the button) = how many milliseoconds passed!

but my code had an bug and error. my useEffect didn't go what I wanted.. It didn't memorized the time when user entered the page.

console said :

👉undefined

and when first hit:

-1611798597788milliseconds passed

(it worked well as I planned when second hit. weird 🤔)

here's my code:

const UserTimer = () => {
  const [startTime, setStartTime] = useState(null);
  const [endTime, setEndTime] = useState(0);
  const [diff, setDiff] = useState(0);

  useEffect(() => {
    let now = new Date();
    setStartTime(now.getTime());
    console.log('👉' + startTime);
  }, []);

  const onClick = () => {
    setEndTime(Date.now());
    setDiff(endTime - startTime);
    setStartTime(endTime);
  };

  return (
    <div>
      <p>{diff}milliseconds passed</p>
      <button onClick={onClick}>click here</button>
    </div>
  );
};

thank you in advance.


Solution

  • setState does not happen synchronously, so you will not see it change instantly. Best to set a variable then use that variable for your math.

    Maybe something like this?

    const UserTimer = () => {
    const [startTime, setStartTime] = React.useState(null);
    const [diff, setDiff] = React.useState(0);
    
    React.useEffect(() => {
      const now = Date.now()
      setStartTime(Date.now());
      console.log('👉' + now);
    }, []);
    
    const onClick = () => {
      const endTime = Date.now()
      setDiff(endTime - startTime);
      setStartTime(endTime);
    };
    
    return (
      <div>
        <p>{diff}milliseconds passed</p>
        <button onClick={onClick}>click here</button>
      </div>
    );
    };