useRef

useRef is a hook in React that returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Here is an example of how you might use useRef in a functional React component:

import { useRef } from 'react';

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

  const handleClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}

In this example, the handleClick function uses the focus method to set focus on the text input element when the button is clicked. The inputEl ref is created by calling useRef with an initial value of null, and it is attached to the input element via the ref attribute.

You might use useRef when you need a reference to an DOM element or a class instance in a functional component. For example, you might use it to set focus on an input element, or to access the value of an input element from within an event handler.

When to use React useRef() ?

React’s useRef hook is typically used in the following situations:

  1. Accessing DOM elements: You can use useRef to create a reference to a DOM element and then access it to manipulate its properties or call its methods.
  2. Storing mutable values: You can use useRef to store mutable values that should persist across re-renders, such as a timer or a subscription, without causing the component to re-render.
  3. Creating a ref to a class component instance: You can use useRef to create a reference to a class component instance and then access its methods or properties.
  4. Creating a ref with callback or with a initial value.

Keep in mind that useRef is not a replacement for state, but should be used in addition to state when you need to hold on to a value without re-rendering the component.

useRef