Referencing a value
that is NOT needed for rendering
// syntax const ref = useRef(initialValue); // usage import { useRef } from 'react'; function MyComponent() { const intervalRef = useRef(0); const inputRef = useRef(null); // ... };
Returns an object
with a single property: current
current
is initially set to value passed to initialValue
passedref
valueTo change the value inside of a ref
by manually changing the property ref.current
function handleStartClick() { const intervalId = setInterval(() => { // ... }, 1000); intervalRef.current = intervalId; }
Changing a ref
does not trigger a re-render
state
variable which trigger a re-renderCan store information between re-renders
Information is local to each copy of your component
useRef
can become useful when directly manipulating DOM content
React updates the reference to point to the element when passed to ref
attribute
// initialize with DOM element type to reference const headerDropdown = useRef<HTMLDetailsElement>(null); return( <> {/* ref must be placed directly on jsx element */} <details className="w-full" ref={headerDropdown}> Text </details> <button onClick={() => { // current is used to access the ref value headerDropdown.current &&headerDropdown.current.removeAttribute('open')! }} > "button" </button> </> )