DEV Community

Cover image for Mastering useRef Hook in React: Unleashing the Power of References
Sayuj Sehgal
Sayuj Sehgal

Posted on

Mastering useRef Hook in React: Unleashing the Power of References

If you like this blog, you can visit my personal blog sehgaltech for more content.

The useRef hook is a function in React that allows you to access and interact with elements in the DOM or mutable variables in your component. It returns a mutable ref object whose .current property is initialized with the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Unlike useState, which re-renders the component when the state changes, useRef maintains its value between renders without causing re-renders. This makes it ideal for storing references to DOM elements, managing focus, implementing animations, and more.

Advantages:

  1. It can be used to store a mutable variable that doesn't cause a re-render when it changes. This is useful for keeping track of intervals, timeouts, or any other information that should persist across renders but doesn't need to trigger an update.
  2. It can be used to access DOM nodes directly, which is useful for managing focus, text selection, or media playback.

Disadvantages:

  1. Overuse of useRef to manipulate the DOM directly can lead to spaghetti code, which is harder to maintain and reason about. It's generally better to use React's declarative style of programming when possible.
  2. It doesn't trigger a re-render when the data changes. This can be an advantage in some cases, but it can also lead to bugs if you're not careful, as your UI won't automatically update to reflect changes in the ref's current value.

Here's an example of how you might use useRef:

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

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

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

  useEffect(() => {
    // This would autofocus the input element on initial render
    inputEl.current.focus();
  }, []); // Empty array ensures that effect runs only once

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

export default TextInputWithFocusButton;

Enter fullscreen mode Exit fullscreen mode

In this example, useRef is used to store a reference to an input element. The focus method is then called on this reference when the button is clicked, focusing the input element.

Conclusion

The useRef hook in React provides a powerful mechanism for managing references within functional components. Whether you're working with DOM elements, preserving values between renders, useRef offers a flexible and efficient solution. By understanding its capabilities and best practices, you can leverage useRef to streamline your React development workflow, enhance code readability, and build more sophisticated and interactive user interfaces.

If you like this blog, you can visit my personal blog sehgaltech for more content.

Top comments (0)