The Power of the useRef Hook in React

Shariq AnsariShariq Ansari
3 min read

React's hook system has undoubtedly revolutionized the way we write React components. From state management with useState to effect handling with useEffect, hooks have made our React code more concise and readable. One of the more versatile hooks in the React arsenal is the useRef hook. In this blog post, we'll deep dive into the useRef hook and explore its uses, supported with practical code examples.

What is useRef?

The useRef hook is typically used to access the DOM directly, but it can do more than just that. Essentially, useRef returns a mutable ref object with a current property. This object persists for the entire lifetime of the component, making it great for preserving values without causing a re-render.

Use Cases for useRef

  1. Directly Accessing DOM Elements: This is the most common use case for useRef.

    Let's take a look at an example where we want to focus on an input field as soon as our component mounts:

     import React, { useEffect, useRef } from 'react';
    
     function AutoFocusInput() {
       const inputRef = useRef(null);
    
       useEffect(() => {
         inputRef.current.focus();
       }, []);
    
       return <input ref={inputRef} />;
     }
    

    Here, the input element is associated with the ref object using the ref prop. We then utilize useEffect to focus on this input when the component mounts.

  2. Preserving Values Without Causing Re-renders:

    In class components, developers often use instance variables to store values that shouldn't trigger a re-render. In functional components, useRef can serve a similar purpose. The values it holds don't cause a component to re-render, making it a good fit for preserving values that you don't want to put in the state.

    Let’s assume you want to track how many times a user clicks a button, but you don't want to re-render the component every time the count changes:

     import React, { useRef } from 'react';
    
     function ClickCounter() {
       const count = useRef(0);
    
       const handleClick = () => {
         count.current += 1;
         console.log(`Button clicked ${count.current} times`);
       };
    
       return <button onClick={handleClick}>Click Me</button>;
     }
    
    1. Storing Previous State or Props:

      Sometimes, we may need to compare the previous and current values of props or state. useRef can come in handy in such scenarios:

       import React, { useState, useEffect, useRef } from 'react';
      
       function DisplayPrevValue() {
         const [value, setValue] = useState('');
         const prevValue = useRef();
      
         useEffect(() => {
           prevValue.current = value;
         }, [value]);
      
         return (
           <div>
             <input value={value} onChange={e => setValue(e.target.value)} />
             <p>Current Value: {value}</p>
             <p>Previous Value: {prevValue.current}</p>
           </div>
         );
       }
      
      1. In the code above, we store the previous value in prevValue using useRef. With useEffect, we update the prevValue whenever our value changes.

Conclusion

The useRef hook in React is a powerful tool, often associated with DOM manipulation. However, as we've seen, its capabilities go beyond just the DOM. Whether you're preserving values without triggering re-renders or tracking previous prop and state values, useRef has got you covered.

Remember, while useRef provides us with direct access and manipulation capabilities, it's essential to use it judiciously. Overuse or misuse can lead to unexpected behavior in your applications.

0
Subscribe to my newsletter

Read articles from Shariq Ansari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shariq Ansari
Shariq Ansari