Skip to content

[Suggestion]: Code example for StopWatch in "Referencing Values with Refs" #7303

Open
@brooklynb7

Description

@brooklynb7

Summary

In the code sample of StopWatch, the DOM's re-rendering only depends on secondsPassed. now and startTime are just used for calculation. If they are treated as state, then very change on them will cause the re-rendering. Am I right?

Page

https://react.dev/learn/referencing-values-with-refs

Details

My suggestion is:

  • define now and startTime as ref
  • define secondPassed as state
import { useState, useRef } from "react";

export default function Stopwatch() {
  const startTime = useRef(null);
  const now = useRef(null);
  const [secondPassed, setSecondPassed] = useState(0);
  const intervalRef = useRef(null);

  function handleStart() {
    startTime.current = Date.now();
    now.current = Date.now();

    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      now.current = Date.now();

      if (startTime != null && now != null) {
        setSecondPassed((now.current - startTime.current) / 1000);
      }
    }, 10);
  }

  function handleStop() {
    clearInterval(intervalRef.current);
  }

  return (
    <>
      <h1>Hi, Time passed: {secondPassed.toFixed(3)}</h1>
      <button onClick={handleStart}>Start</button>
      <button onClick={handleStop}>Stop</button>
    </>
  );
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions