DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

useRef in React (easy language)

Certainly! useRef is a hook in React that allows you to access and interact with a DOM element or keep a mutable reference to a value that doesn't trigger re-renders when it changes.

Easy Explanation:
Imagine you have a physical notebook where you jot down notes. This notebook doesn't shout at you every time you make a change in it, but you can always refer back to it whenever you need to see what you've written. Similarly, useRef is like this notebook. You can keep track of certain things without the entire room (your component) reacting every time you make a note.

Common use cases:

  1. Focus on an input field.
  2. Measure the dimensions of an element.
  3. Keep track of the previous state/value of a variable without causing re-renders.

Advanced Explanation:

  1. Mutable Reference Object:

    • useRef returns a mutable reference object ({ current: ... }).
    • The current property is initialized to the passed argument (initialValue) which can be anything. It remains persistent for the full lifetime of the component.
    • Unlike state variables using useState, changing ref.current doesn't trigger re-renders.
  2. DOM Access:

    • When used in conjunction with the ref attribute on an element, it provides direct access to the DOM element. This is especially useful when integrating with third-party libraries or for tasks like setting focus or measuring elements.
  3. Previous Values:

    • It can be used to store the previous value/state of a variable. Because it doesn't cause a re-render on change, it can be handy to check previous vs current values without costly re-renders.
  4. Timers and Intervals:

    • Using useRef is a common pattern to hold references to intervals or timeouts. This way, you can clear them later (like in a useEffect cleanup).
  5. Imperative Handle:

    • Used in conjunction with forwardRef and useImperativeHandle, it allows parent components to access the functions and values of child components. It's a more advanced pattern for rare use cases where parents need to call child functions directly.

Example of accessing a DOM element:

function MyComponent() {
  const inputRef = useRef(null);

  const handleFocus = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleFocus}>Focus the input</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the inputRef is attached to the input field, and when the button is clicked, the input field gets focused.

Remember, while useRef can be powerful, direct manipulation of the DOM is against the declarative nature of React. It's wise to use it judiciously and only when necessary.

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/

Top comments (0)