HomeToolsAbout a20k

useRef

What is it

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); // ... };

Return Value

Returns an object with a single property: current

  • current is initially set to value passed to initialValue passed

Changing ref value

To change the value inside of a ref by manually changing the property ref.current

function handleStartClick() { const intervalId = setInterval(() => { // ... }, 1000); intervalRef.current = intervalId; }

Behavior

Changing a ref does not trigger a re-render

  • unlike state variable which trigger a re-render

Can store information between re-renders

  • unlike regular variables which reset on every render)

Information is local to each copy of your component

  • unlike the variables outside which are shared

Strategies

useRef can become useful when directly manipulating DOM content

React updates the reference to point to the element when passed to ref attribute

  • When React creaets a DOM node for theis element, it attaches the reference to the node. This is a native feature/support of React.
// 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> </> )
© VincentVanKoh