Closed Gazook89 closed 1 month ago
We should gradually convert all of these to functional components anyway (which uses "useRef" instead of "createRef"). Here are my personal notes on how to use REFS with functional components:
By using a ref, you ensure that:
Changing a ref does not trigger a re-render, so refs are not appropriate for storing information you want to display on the screen. Use state for that instead.
Call useRef
at the top level of your component to declare one or more refs.
import { useRef } from 'react';
function Stopwatch() {
const intervalRef = useRef(0);
// ...
useRef
returns a ref object with a single current
property initially set to the initial value you provided.
On the next renders, useRef
will return the same object. You can change its current
property to store information and read it later. This might remind you of state, but there is an important difference.
Changing a ref does not trigger a re-render. This means refs are perfect for storing information that doesn’t affect the visual output of your component. For example, if you need to store an interval ID and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its current
property:
function handleStartClick() {
const intervalId = setInterval(() => {
// ...
}, 1000);
intervalRef.current = intervalId;
}
Later, you can read that interval ID from the ref so that you can call clear that interval:
function handleStopClick() {
const intervalId = intervalRef.current;
clearInterval(intervalId);
}
Do you want to combine this ref work with functional component work? If so, this issue could be renamed to indicate the much larger task of doing that (and refs would be one small part). Perhaps as a Project, and separate out each component as a separate Issue?
However you want is fine with me.
Renderer
v3
Browser
Chrome
Operating System
MacOS
What happened?
React is emitting many of these errors in the browser console:
for the following files:
Anything that looks like
ref='....'
should be changed to usecreateRef()
: More info on old React docs.This might be a good first issue? Maybe not all at once? Nothing is currently broken and likely won't be for awhile. It is annoying seeing the Errors in console, though.
Code
No response