reactjs / reactjs/react.dev

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

Open
#7,303 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: documentation
Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

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>
    </>
  );
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Open the Referencing Values with Refs page linked in the issue and review the StopWatch example. Compare its handling of now, startTime, and secondsPassed with the suggested ref/state split, then update the example if appropriate. Done means the page’s code clearly demonstrates which values trigger re-renders and which are stored in refs.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.