useRef in React

Expert-Level Explanation

useRef is a hook that returns a mutable ref object whose .current property is initialised with the passed argument. The object returned from useRef will persist for the full lifetime of the component. It’s commonly used for accessing a DOM element directly, but it can also be used to keep any mutable value around, similar to how you’d use instance fields in classes.

Creative Explanation

Think of useRef as a personal notebook that a component keeps. This notebook can hold onto a piece of information (like a reference to a DOM element) throughout the component's life. The content of the notebook can change, but the notebook itself stays with the component.

Practical Explanation with Code

Example of using useRef:

import React, { useRef, useEffect } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  useEffect(() => {
    // Automatically focus the input
    inputEl.current.focus();
  }, []);

  return (
    <input ref={inputEl} type="text" />
  );
}

In this example, useRef is used to store a reference to an input DOM element.

Real-World Example

In an online chat application, useRef can be used to keep a reference to the latest message. This allows the application to automatically scroll to the latest message when it is added, enhancing the user experience.