ReactJS – useRef hook

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to create a reference to any DOM element in a functional component.

This hook is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM.

If we pass a ref object to any DOM element, then the .current property to the corresponding DOM node elements will be added whenever the node changes.


const refContainer = useRef(initialValue);


In this example, we will build a React application that passes the ref object to two input fields.

When clicked on a button, it will automatically fetch the data of these input fields.


import React, { useRef } from 'react';

function App() {

   const email = useRef(null);
   const username = useRef(null);

   const fetchEmail = () => {
      email.current.value = '';
   const fetchUsername = () => {
      username.current.value = 'RahulBansal123';
   return (
            <input placeholder="Username" ref={username} />
            <input placeholder="Email" ref={email} />
         <button onClick={fetchUsername}>Username</button>
         <button onClick={fetchEmail}>Email</button>
export default App;

In the above example, when the Username or Email button is clicked, the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from NULL to some text.


This will produce the following result.

Updated on 19-Mar-2021 11:00:49