Open In App

What is significance of refs in ReactJS ?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them.  We can create a Ref by the following three methods:

Prerequisites

Method 1: Using React.createRef()

It was introduced in React 16.3. We can create a ref variable using React.createRef() and attach it to the React element by using the ref attribute of the element.

Syntax: 

const func = React.createRef();

Method 2: Using useRef() hook

We cannot use the ref attribute in the functional components because they don’t have the instances. To use the ref functionality in the functional component we can use the useRef hook.



Syntax:

const func = useRef(null);

Method 3: Using callback ref

 This method was used before React 16.3 version. So if you are using React<16.3 you will use this method. In this method, we pass a function instead of passing a ref attribute that is created by createRef() or useRef(). The function receives the React element or HTML DOM element as an argument, which can be used.

Syntax:

let textInput = null;
// Callback function that will set ref for input field
const setTextInputRef = (element) => {
textInputRef = element;
};

Example: This example implements refs by using createRef method.




// Filname - App.js
import * as React from "react";
 
const App = () => {
    // Creating textInputRef variable
    const textInputRef = React.createRef();
 
    // This method will be used to focus textInput
    // and give background color to textInput field
    const textInputFocusHandler = () => {
        // Focusing input element
        textInputRef.current.focus();
 
        // Giving background color to input element
        textInputRef.current.style.background = "green";
    };
 
    return (
        <div
            style={{ textAlign: "center", margin: "auto" }}
        >
            <h1 style={{ color: "green" }}>
                GeeksforGeeks
            </h1>
            <h3>React Example of Using Refs</h3>
 
            {/* Attaching ref variable using
                element's ref attribute */}
            <input ref={textInputRef} type="text" />
 
            {/* Attaching textInputFocusHandler   
                method to button click */}
            <button onClick={textInputFocusHandler}>
                Focus
            </button>
        </div>
    );
};
 
export default App;

Steps to Run: Use this command in the terminal inside the project directory.

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.

Significance of Refs in React JS:

Note: We should only use Refs when it is really necessary. It should be avoided to do the things that can be done declaratively. 


Article Tags :