useRef

useRef

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). It is used for persistent mutable values and DOM elements.

const myRef = useRef(initialValue);

// refs are updated either inside a useEffect() or inside handlers
const handler = () => {
  // get reference value
  const currentValue = myRef.current;
  
  //...
  // set a new reference value
  myRef.current = newValue; 
};

🚀 Example. Accessing the DOM using ref (focusing and blurring the HTML element).


 const Ref = () => {
  const textAreaRef = useRef(null);

  return (
    <>
      <button onClick={() => textAreaRef.current?.focus()}>
        Focus on the text area
      </button>

      <button onClick={() => textAreaRef.current?.blur()}>
        Unfocus the text area
      </button>

      <textarea ref={textAreaRef}></textarea>
    </>
  );
};

🚀 Note.

  • Updating a ref value does not trigger re-rendering while setting a new state value makes the component re-render; The reference update is synchronous.
  • The updated ref value is available right away, while the state update is asynchronous (the state is updated after re-rendering).