Primary Uses of useRef

1. Accessing DOM elements

Referring to DOM elements directly within your component is a common use case for useRef. Instead of employing DOM queries like document.getElementById, useRef allows direct referencing of elements.

Javascript




import React, { useRef } from 'react';
 
const CustomComponent = () => {
    const inputRef = useRef(null);
 
    const handleClick = () => {
        // Focus the input element on button click
        inputRef.current.focus();
    };
 
    return (
        <div>
            <input ref={inputRef} type="text" />
            <button
                onClick={handleClick}>
                Focus Input
            </button>
        </div>
    );
};


2. Storing previous values

Utilizing useRef enables the storage of a value that persists across renders without triggering re-rendering when updated. This proves beneficial for maintaining previous values without causing unnecessary renders.

Javascript




import React, {
    useEffect,
    useRef
} from 'react';
 
const CustomValueComponent = ({ value }) => {
    const prevValueRef = useRef();
 
    useEffect(() => {
        prevValueRef.current = value;
    }, [value]);
 
    return (
        <div>
            <p>Current Value: {value}</p>
            <p>Previous Value: {prevValueRef.current}</p>
        </div>
    );
};


3. Navigating External Libraries

In certain scenarios, when incorporating external libraries that require a mutable reference to data, useRef can prove to be quite useful. Keep in mind that as useRef doesn’t induce re-renders, if you require component updates to be reflected in the UI, useState should be preferred. Reserve the use of useRef for managing mutable values or references without influencing component rendering.

Javascript




import React, {
    useEffect,
    useRef
} from 'react';
import externalLibrary from 'some-external-library';
 
const CustomLibraryComponent = () => {
    const dataRef = useRef([]);
 
    useEffect(() => {
        // Update the external library with the latest data
        externalLibrary.updateData(dataRef.current);
    }, []);
 
    //...
};


How useRef Hook is useful in React ?

Hooks provides a way to useState and other React features in functional components without the need for class components. We can either use built-in hooks or customize and make our own. One of those hooks in useRef. It allows reference to a value that does not require rendering. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

Table of Content

  • Primary Uses of useRef:
  • useImperativeHandle
  • Conclusion

Similar Reads

Primary Uses of useRef:

1. Accessing DOM elements...

useImperativeHandle:

...

Steps to Create a React App:

...

Conclusion:

...

Contact Us