How to use useRef() in React JS

Whenever we want to access data of input elements we use useState() hook to get input forms values or some other hooks, and this basically helps to manage to react states.

But not all the time we need to manage to react state, sometimes we just want to access the HTML element values for just reading purposes.

Refs are basically the reference to the Dom elements.

So if we want to get values of input fields without taking care of react states or without using useState(), then we can use Refs.

Let’s understand this with the help of code.

Here we created a component file with the name Refs.js, and we are calling this component inside the App.js file.

import './App.css';
import Refs from './Refs';

function App() {
  return (
   <>
    <Refs/>
   </>
  );
}

export default App;

Now inside the Refs.js file, we have created a form with an input field for taking input as a username, this form is submitted when the user clicks on submit button, on submit of this form a method called submitData is executing.

First, let’s see the Refs.js file code and then understand it.

import React,{useRef} from 'react';
const Refs= ()=>{
    const username = useRef();
    const submitData=(event)=>{
        event.preventDefault();
        console.log(username);
        console.log(username.current.value);
    }
    return (
        <form onSubmit={submitData}>
            <input type="text" placeholder='Enter Username' ref={username}/>
            <button type="submit">Submit</button><br/>
            
        </form>
    )
}
export default Refs;

Before doing anything first we need to import this useRef hook and we have to assign it to a constant variable username.

const username = useRef();

This username is referencing the input type text filed with this property ref={username}

<input type="text" placeholder='Enter Username' ref={username}/>

Now submitData function we are displaying this reference variable value.

As it is an HTML DOM reference variable, it has many properties, and it returns an object with different properties.

We can access this variable value by its properties, username.current.value

So whatever we write inside the input text we can get that value by using this username.current.value

Here is the output which helps you to visualize the actual work.

On the above image, you can see we console the username and we got this object which has a current property that has a value property so by consoling username.current.value we can get the name we have entered in the input field.

Controlled and Uncontrolled components :

So basically component which uses useState or other hooks to manage to react states is a controlled component and which uses Refs for getting the value of input fields is uncontrolled components because with Refs we cannot manage to react states.

Related Posts

frontbackgeek-images

Unveiling React Query: Building a Task Manager App with useMutation and useQuery Hooks

In this article, we will build a Task Manager app to understand What is React Query? and How to use React Query useMutation, and React Query useQuery…

frontbackgeek-images

Building Forms with Formik in React: Complete Code Examples and Explanations

In this article, we are building a simple form to understand how to build a form with Formik in React application, Here we are building a simple…

frontbackgeek-images

Creating React antd table with sorting and pagination and using antd select and antd modal for filtering and displaying the data.

In this article we are creating an antd table with React antd library, antd library is an ant design library, which has a rich set of components…

frontbackgeek-images

React Virtualized Tables: Enhancing the Performance of React 18 Applications

In this article, we will explore the concept of React Virtualized Tables as a solution to enhance performance in rendering large tables. We will delve into what…

React Native Expo Error Solution : ERROR Invariant Violation: “main” has not been registered. This can happen if: * Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it, and restart it in the current project.

Solution is Reinstall with this Restart and Rescan the app

frontbackgeek-images

Exploring useLayoutEffect VS useEffect in React 18: A Deep Dive with Code Examples and Practical Comparisons

In React.js, Hooks are very important for handling state and for other features related to functional components, useLayoutEffect vs useEffect is a hot topic, because both are…

Leave a Reply

Your email address will not be published. Required fields are marked *