DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Mastering React's useRef Hook: Working with DOM and Mutable Values

useRef Hook in React

The useRef hook is a built-in React hook used to persist values across renders without causing re-renders. It's often used to interact with DOM elements directly and to store values that need to persist between renders but do not necessarily need to trigger a re-render.


What is useRef?

The useRef hook is primarily used for two purposes:

  1. Accessing DOM elements: It provides a way to reference DOM nodes or React elements directly, allowing you to interact with them imperatively.
  2. Persisting values across renders: It can store mutable values that won't trigger a re-render when updated, unlike state.

Syntax of useRef

const myRef = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • myRef: A reference object created by useRef.
  • initialValue: The initial value to be stored in the reference object. This can be anything, such as a DOM node, an object, or a primitive value.

The reference object returned by useRef has a current property, which is where the actual value is stored.


How useRef Works

  1. Accessing DOM Elements: You can use useRef to get direct access to a DOM element in a functional component, just like the ref attribute in class components.
   const MyComponent = () => {
     const inputRef = useRef(null);

     const focusInput = () => {
       // Access the DOM node and focus it
       inputRef.current.focus();
     };

     return (
       <div>
         <input ref={inputRef} />
         <button onClick={focusInput}>Focus Input</button>
       </div>
     );
   };
Enter fullscreen mode Exit fullscreen mode
  • Here, inputRef is used to reference the <input> element, and the focusInput function focuses on that input element when the button is clicked.
  1. Storing Mutable Values Across Renders: You can use useRef to store a value that persists across renders but does not trigger a re-render when changed.
   const TimerComponent = () => {
     const countRef = useRef(0);

     const increment = () => {
       countRef.current++;
       console.log(countRef.current);  // This will log the updated value
     };

     return (
       <div>
         <p>Current count (does not trigger re-render): {countRef.current}</p>
         <button onClick={increment}>Increment</button>
       </div>
     );
   };
Enter fullscreen mode Exit fullscreen mode
  • In this example, countRef stores a mutable value. The value can be updated without causing a re-render, unlike useState, which triggers a re-render.

Common Use Cases of useRef

  1. Accessing DOM Elements: For example, focusing an input field, scrolling to a specific element, or measuring the size of an element.
   const ScrollToTop = () => {
     const topRef = useRef(null);

     const scrollToTop = () => {
       topRef.current.scrollIntoView({ behavior: 'smooth' });
     };

     return (
       <div>
         <div ref={topRef} style={{ height: '2000px' }}>
           Scroll to me!
         </div>
         <button onClick={scrollToTop}>Scroll to Top</button>
       </div>
     );
   };
Enter fullscreen mode Exit fullscreen mode
  1. Storing Previous State: If you need to track the previous value of a prop or state value.
   const PreviousState = ({ count }) => {
     const prevCountRef = useRef();

     useEffect(() => {
       prevCountRef.current = count; // Store the current value in the ref
     }, [count]);

     return (
       <div>
         <p>Current Count: {count}</p>
         <p>Previous Count: {prevCountRef.current}</p>
       </div>
     );
   };
Enter fullscreen mode Exit fullscreen mode
  • Explanation: prevCountRef stores the previous value of count, which can be accessed without triggering a re-render.
  1. Avoiding Re-renders for Complex Values: If you have a large object or complex data structure that doesn't need to trigger a re-render, useRef can store it without affecting the component’s performance.

  2. Tracking Interval or Timeout: You can store IDs of timeouts or intervals to clear them later.

   const Timer = () => {
     const intervalRef = useRef();

     useEffect(() => {
       intervalRef.current = setInterval(() => {
         console.log('Timer running');
       }, 1000);

       return () => clearInterval(intervalRef.current);
     }, []);

     return <p>Timer is running...</p>;
   };
Enter fullscreen mode Exit fullscreen mode
  • Explanation: intervalRef stores the ID of the interval, and it can be used to clear the interval when the component unmounts.

Key Differences Between useRef and useState

Feature useRef useState
Triggers re-render No (does not trigger a re-render) Yes (triggers a re-render when state changes)
Use Case Storing mutable values or DOM references Storing state that affects rendering
Value storage Stored in current property Stored in state variable
Persistence across renders Yes (keeps value across renders without triggering re-render) Yes (but triggers re-render when updated)

Example: Using useRef for Form Validation

Here’s an example where useRef is used for form validation, focusing on an input field when it’s invalid.

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

const FormComponent = () => {
  const inputRef = useRef();
  const [inputValue, setInputValue] = useState('');
  const [error, setError] = useState('');

  const validateInput = () => {
    if (inputValue === '') {
      setError('Input cannot be empty');
      inputRef.current.focus(); // Focus the input element
    } else {
      setError('');
    }
  };

  return (
    <div>
      <input
        ref={inputRef}
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <button onClick={validateInput}>Submit</button>
    </div>
  );
};

export default FormComponent;
Enter fullscreen mode Exit fullscreen mode
  • Explanation:
    • The inputRef is used to focus on the input element if the input value is empty.
    • This functionality wouldn't be possible with useState because focusing on a DOM element requires direct access to the element, which useState cannot provide.

Summary of useRef Hook

  • useRef is used to store references to DOM elements and mutable values that don’t trigger re-renders when updated.
  • It is useful for accessing DOM nodes directly (e.g., for focusing, scrolling, or animations).
  • useRef is also handy for storing values that persist across renders without needing to trigger a re-render, such as tracking previous values or storing timeout/interval IDs.
  • Key Difference: Unlike useState, updating useRef does not trigger a re-render.

Conclusion

The useRef hook is incredibly useful for dealing with mutable values and direct DOM manipulation in React. Whether you're working with form elements, tracking the previous state, or interacting with third-party libraries, useRef provides a clean, efficient solution. By using useRef, you can maintain persistence without triggering unnecessary re-renders, which makes it a great choice for performance-sensitive operations.


Top comments (0)