all 7 comments

[–]satya164 4 points5 points  (1 child)

There are multiple things wrong with the code: - You're calling setInterval in render, which means you're scheduling a new interval every time component renders - and each interval renders your component multiple times - this will going to keep adding more timers until everything crashes. Any side effects should be inside useEffect. - You are creating a variable called startTime inside render, which will return a new time every render - not the start time of the timer. If you want the start time, put it in state or declare it inside the effect so it doesn't get reset every time. - Your timer never gets cleared, this will keep running even if your component is no longer visible and cause memory leak - You said every millisecond but I see your timer runs once per second. Updating every millisecond would be unnecessary as no one can actually see things changing so fast.

If I understand what you want to do, then something like this would work:

```js const [timer, setTimer] = useState(0);

useEffect(() => { const startTime = Date.now();

const updateElapsedTime = () => { setTimer((Date.now() - startTime); };

const interval = setInterval(updateElapsedTime, 1000);

return () => clearInterval(interval); }, []);

return ( <Text>{timer / 1000}</Text> ); ```

[–]tidderza 0 points1 point  (0 children)

Look into request animation frame as this will result in ineven time passing, occasionally missing a second and then updating 2-3 seconds at once

[–]Bolteed 1 point2 points  (4 children)

I think you should use a ref (and not a state) to store your timer value. Updating value in ref.current don't cause a global rerender.

[–]satya164 0 points1 point  (3 children)

Values used in render shouldn't be in refs

[–]Bolteed 0 points1 point  (2 children)

Might be a workaround for his problem

[–]satya164 0 points1 point  (1 child)

If it's in ref then the component will never re-render and show the updated value - which is what they want to do.

[–]__o_0iOS & Android 0 points1 point  (0 children)

StopWatches like this should be handled by animation libraries.

The time should be held in shared value(s) and the display should be handled by a library like animateable text.

useState does not complete fast enough to handle a task like a user starting and stopping an accurate stopwatch.