useRef
https://frontendmasters.com/courses/intermediate-react-v2/useref/
Hooks in Depth
This is where hooks is getting hard...
// **** Ref.js ****
import React, { useState, useEffect, useRef } from "react";
const RefComponent = () => {
const [stateNumber, setStateNumber] = useState(0);
const numRef = useRef(0);
// **** 1. here the stateNumber and numRef. ↴
// won't match
// they are incremented at the same time,
// but they are not the same
// stateNumber "lags" behind
function incrementAndDelayLogging() {
// what's going on, is that this `stateNumber` below, is
// is holding onto the previous iteration
// because of closure
setStateNumber(stateNumber + 1);
// while numRef is always holding onto to the
// CURRENT value
numRef.current++;
setTimeout(
() => alert(`state: ${stateNumber} | ref: ${numRef.current}`),
1000
);
}
return (
<div>
<h1>useRef Example</h1>
<button onClick={incrementAndDelayLogging}>delay logging</button>
<h4>state: {stateNumber}</h4>
<h4>ref: {numRef.current}</h4>
</div>
);
};
export default RefComponent;
Usefulness of useRef
They resolve this closure problem, that they always point to the latest value and can be called in any context.
If we were using class components, we could just create an instance, but since these are functional components we need to use refs.
can only use ref.current
Notice, that you can only use .current
here, no other property, the object is sealed.
It's useful to hold on to DOM elements, intervals, etc.