useRef Hook in React JS – Use Cases

Lets us have a look on What is the use of useRef hook in React JS. What are the various use cases in which useRef hook can help build our react app easily. Also, we can look into example code with useRef hook usage in react js.

Importing useRef in React JS

import { useRef } from "react";

Uses of useRef hook in React App

  • To reference the DOM elements
  • For storing the previous state
  • Hold mutable value prevent re-render of component

Referencing the DOM elements with useRef

eg: if we want to shift focus to an input field after a button click

useRef Hook in React JS - Use Cases
On clicking the reset button, my cursor focus should go to the input field so I can enter a new name. So here we can make use of the useRef hook to access the DOM element.

  const inputElementReference = useRef("");    
  
  console.log(inputElementReference);  // return object with current value ""

Example:

  import React, { useRef } from "react";

  function App() {
  
     const inputElementReference = useRef("");    
     
     const resetInput = () => {
        
        inputElementReference.current.focus();

     };
  

     return(
       <div>
          <Input  
            ref={inputElementReference}
            type="text"
         />

         <button onClick={resetInput}> Reset  </button>
       
       <div>

     )
 }  

About the Author: smartcoder

You might like

Leave a Reply

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