[Suggestion]: Code example for StopWatch in "Referencing Values with Refs"
Nobody has claimed this yet.
- 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
nowandstartTimeasref - define
secondPassedasstate
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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