Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
brooklynb7 opened this issue Nov 21, 2024 · 0 comments

Comments

@brooklynb7
Copy link

brooklynb7 commented Nov 21, 2024

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>
    </>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant