Skip to main content
Updated date:

The UseRef Hook in React Js

Saleh is an experienced Web Developer and uses his knowledge and experience to guide people looking to learn Web Dev and new technologies

This article will provide you with lots of information about the useRef hook in Js, including what it does and how to use it.

This article will provide you with lots of information about the useRef hook in Js, including what it does and how to use it.

In this tutorial, we will learn about the useRef hook in React JS and its uses, as well as take a look at a demo that will take user input and save it in a reference or ref. You will also learn how to use the useRef hook to create persisted mutable values (also known as references).

The useRef hook is a built-in React hook that takes one argument or parameter as its initial value and returns a reference. The reference has an interesting and useful property called current.

Features of useRef

One of the most useful features of the useRef hook is that the data or value in a reference or ref remains the same, even after component re-rendering. Also, if you update a reference, it does not affect the rendering of the app, unlike states.

useRef vs useState

  1. References do not affect component rendering but states do.
  2. useState returns two properties or an array. One is the value or state and the other is the function to update the state. In contrast, useRef returns only one value, which is the actual data stored.
  3. When the reference value is changed, it is updated without the need to refresh or re-render. However in useState, the component must render again to update the state or its value.

When to Use Refs and States

Refs are useful when getting user input, DOM element properties and storing constantly updating values.

If you are storing component related info or use methods in components, however, states are the best option.

Getting Started

We will now create a simple application that has a simple form that collects user inputs and saves in the references for later use.

First of all, import the useRef state from React using the following command:

import React, { useRef } from "react"

If you need to learn how to create a react app from scratch, the following video may prove to be useful.

Next, create a few variable references to store different user input data. We will collect the user's name, email and password. This small demo can be a part of a larger login system. To create an empty reference, the useRef() function is used.

Read More From Owlcation

import React, { useRef } from "react"

export default function Signup() {
  //variables to store the refs
  const nameRef = useRef();
  const emailRef = useRef()
  const passwordRef = useRef()

  return (
  )
}

Creating the Form

Next, we will create a simple form to get the user input. The form will have three input fields and a submit button. In each input, we will add a property called ref={}. Inside the curly brackets, we will write the name of the corresponding reference variable. For example, for the name input field, we will write nameRef inside the curly brackets.

<div className="container">
  <form onSubmit={handleSubmit}>
    <div className="input_group">
      <label>Name</label>
      <input type="text" ref={nameRef} />
    </div>
    <div className="input_group">
      <label>Email</label>
      <input type="text" ref={emailRef} />
    </div>
    <div className="input_group">
      <label>Password</label>
      <input type="password" ref={passwordRef} />
    </div>
    <input type="submit" />
  </form>
</div>

In the above code, the method onSubmit in the form tags is used to run a function—in this case, handle Submit—when the user submits the form.

Storing User Details

Right now when the user types anything in the inputs, the value or text will be saved in the reference. Next, we will create the function handle Submit that will run when the user clicks the submit button. In the form, we will display the stored data using console.log() just to check if the data is successfully saved or not. To get the value from the ref, we use refName.current.value, where ref Name is the name of the reference.

function handleSubmit(e) {
  //prevent page from refreshing
  e.preventDefault()
  //output the name
  console.log(nameRef.current.value)
  //output the email
  console.log(emailRef.current.value)
}

In the above code, the prevent default function is used to prevent page refresh on submit.

App.js Complete Code

import React, { useRef } from "react"

export default function App() {
  const nameRef = useRef();
  const emailRef = useRef()
  const passwordRef = useRef()

  function handleSubmit(e) {
    e.preventDefault()
    //output the name
    console.log(nameRef.current.value)
    //output the email
    console.log(emailRef.current.value)
  }

  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
        <div className="input_group">
          <label>Name</label>
          <input type="text" ref={nameRef}/>
        </div>
        <div className="input_group">
          <label>Email</label>
          <input type="text" ref={emailRef}/>
        </div>
        <div className="input_group">
          <label>Password</label>
          <input type="password" ref={passwordRef}/>
        </div>
        <input type="submit"/>
      </form>
    </div>
  )
}

Styling

Now to make the form look better and presentable, add the following file in App.css (create one if you don't have it).

.container {
    width: 100%;
    height: 80vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

form {
    border: 1px solid #000;
    width: 300px;
    height: 230px;
    padding: 20px;
    border-radius: 4px;
    text-align: center;
}

.input_group {
    text-align: center;
    display: flex;
    flex-direction: column;
    row-gap: 10px;
    align-items: center;
}

.input_group input {
    padding: 3px 5px;
    margin-bottom: 5px;
}

input[type="submit"] {
    margin-top: 15px;
    padding: 8px 15px;
    background-color: transparent;
    border: 1.5px solid #000;
    color: #000;
    cursor: pointer;
    transition: 0.2s ease-in-out;
    border-radius: 4px;
}

input[type="submit"]:hover {
    background-color: #000;
    color: #fff;
}

Then import it into App.js

import "./App.css"

Now if you run the app and fill the form and click submit, the data will be saved in the references. You can open the console by right-clicking and selecting inspect. You will see the user's name and email in the console. Each time you submit, it will update asynchronously.

Below are the images of the page and console.

useref
Result

Result

And there you go! Hopefully you have learned what the useRef hook is, its uses, the differences between states and, of course, how to use it.

Until next time!

Cheers!

This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

Related Articles