useRef() Hook- In React js

useRef

When building a React app, there are going to be times where you'll want to reference a particular part of the DOM for one reason or another. If you've written Javascript code before, you're likely very familiar with how you would go about doing this, however In React you'll have to change your ways a bit — luckily it is pretty painless — in comes the useRef hook.

How It Works

The useRef hook simply returns an object with a ".current" property which will be the DOM element or value that you plan to use at some point or another within your component. Note: useRef will not cause any re-renders, it is simply an object that holds the DOM or value you've assigned to it.

How To Use It

  1. Import useRef from React
  2. Create a variable and set the value to useRef()
  3. Place a ref attribute on an element (there are other ways to use this hook, but I'm simply covering the most common / simplest use case), with the value set to the variable created above
  4. Access the DOM element with 'variableName.current'

 
  import React, { useEffect, useRef, useState } from 'react';

  function App() {

    var [name,setName] = useState('')
    var renderCount = useRef(null)

    useEffect(()=>{
      renderCount.current = renderCount.current + 1
    })

    return (
      <div>

        <input value={name} onChange={e=>setName(e.target.value)} />
        <h3>My Name is {name}</h3>
        <h4>I used {renderCount.current} times</h4>

      </div>
    );
  }

  export default App;

Submit form using , useRef Hook

* ref is a data variable


  import {useRef, useEffect} from "react";
  import "./App.css";

  function App(){

      const nameRef= useRef();
      const mailRef = useRef()

      console.log(nameRef)

      useEffect(() => {
          console.log(nameRef);
      }, [])

      const handleSubmit = e => {
        e.preventDefault()
        console.log(nameRef.current.value);
        console.log(mailRef.current.value);
      }

      return (
          <div className="app">
              <form onSubmit={handleSubmit}>
                  <label htmlFor="name">Name</label>
                  <input ref={nameRef} type="text" id="name" />

                  <label htmlFor="email">Email</label>
                  <input ref={mailRef} type="text" id="email" />

                  <button>Submit</button>
              </form>
          </div>
      )
  }

  export default App;