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
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> ) }