Stores a mutable reference to a DOM element or value without causing re-render.
import { useRef } from 'react';
const ref = useRef<HTMLElement>(null);
ref.current
: mutable property containing the referenced DOM element or value.ref.current
doesn't trigger re-render.import { useRef } from 'react';
function TextInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = (): void => {
inputRef.current?.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
}
inputRef
references the actual <input>
DOM node..current
is initially null
until component mounts..focus()
, .scrollIntoView()
).setInterval
, setTimeout
.const intervalRef = useRef<number | null>(null);
useEffect(() => {
intervalRef.current = window.setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, []);
const [count, setCount] = useState(0);
const prevCountRef = useRef<number>();
useEffect(() => {
prevCountRef.current = count;
}, [count]);
const prev = prevCountRef.current;