What is so special about : useRef() react hook
Tags: javascript, react, beginners, tutorial
Published: 2022-07-14 09:34:10

#What is useRef() ?
useRef() is a react hook used for references in React, to store a reference to particular DOM nodes or React elements, to access React DOM nodes or React elements, to interact with React DOM nodes or React elements and to change the value of a child component, without using props.

But wait what ? without using props!🤔Sounds cool 🤩

#what makes useRef() hook so special?
The useRef() hook persists in between component renders (like state).Also the useRef value resides outside of the render cycle, it is possible to modify it without triggering your component to re-update.

Syntax and how to useRef?

```react
 import { useRef } from "react"
```
useRef is a hook which returns an object with a current property set to the value passed to the hook.

For instance this:
```react
const referenceNum = useRef(0);
```
 referenceNum is initialised as an object with a `current ` property would return an object like so:
{current: 0};
referenceNum.current holds the value 0

The current property can be altered because this object is changeable.

The "current" property of React elements can be set to be the actual DOM node that the element is rendered to by using the ref attribute. In this manner, the reference can be used for traditional DOM manipulation, such as adding event listeners.

Now, you all might be thinking how to get reference of DOM element.
Well, we can use the** ref **attribute of React elements to set the “current” property to be the actual DOM node the element is rendered to. This way we can use the reference for old school DOM manipulation.

For example:

```react
const divRef = useRef();
const MyComponent = (props) => {
 return <div ref={divRef}> A Div! </div>;
};

```
therefore,
`const divRef = useRef();`
divRef is initialised with the current property set to 'undefined' because we didn’t give a value to the hook.
Then by passing divRef to the ref={} attribute, when the component is mounted to the DOM the divRef.current property gets set to the actual DOM node, eg.`"<div>A Div!</div>"`

Let's see the real use case of useRef react hook to better comprehend it.

1. useRef is to get access to DOM elements or to get reference of DOM .For example let's say we have a react app in which we have an input field and button and a variable which gets updated on whatever input field we give.
And show up on the screen .

```react
import React,{useState} from "react"
export default function App() {
 
const [name,setName]=useState("");
 return (
   <div className="App">
    <input
    type="text"
    name="name"
    value={name}
    onChange={(e)=>{
     setName(e.target.value)
    }}
    ></input>
    <button onClick={(e)=>{
       setName("")
    }}>button</button>
    <h2 align="center">{name}</h2>
   </div>
 );
}

```
Functionality is such if we click on button it will clear input field .But will not focus on input field ,coz we don't have access to DOM element,
(you can see the demo by clicking on this link –  
https://codesandbox.io/s/without-using-useref-of8m50?file=/src/App.js )
To focus on the input field that is to access DOM element we use useRef to reset  and get focus on the input field.
Since, we know that useref returns an object with a property called current. When we reference our input element to input tag, then input tag will reference value to this current and to reference **_inputElem _**to input tag => we’ve an attribute called **_ref_**.
`<input ref={inputEle}/>`
Now once we have access to this input element ,we can apply focus on it or on all the properties we have on that html tag.
So,now when we click on button , it will call reset function and we’ll set focus.

```react
import React from "react";
import {useState,useRef} from "react";
function App() {
const [name,setName]=useState("");
const inputEle=useRef("");
console.log(inputEle);
 const resetInput=()=>{
 setName("");
 inputEle.current.focus();
 };
 return (
   <div className="App">
     <div>
    <input
    ref={inputEle}
    name="name"
    type="text"
    value={name}
    onChange={(e)=>setName(e.target.value)}
    />
     <button onClick={resetInput}>button</button>
   </div>
  <div> My Name is {name}</div>
  </div>
 );
}
export default App;
```
Ref doesn't cause your component to re-update, when the state of the component is changed.

2.Another use case of useRef is to stores previous values.

```react
import React, { useEffect,useState,useRef } from "react";
 
function App() {
 
const [counter,setCounter]=useState(0);
 
const prevVal=useRef("");
 
useEffect(()=>{
prevVal.current=counter;
},[counter]);
 
 return (
   <div className="App">
     <div>
       <h3>Random counter: {counter}</h3>
       <p>previous counter:{prevVal.current}</p>
       <button onClick={(e)=>setCounter(Math.ceil(Math.random()*100))}>generate</button>
     </div>
  </div>
 );
}
export default App;
```
Here, if we click on button it will go on generating random number and will store the previous generated number in **_"previous Counter"_** variable and newly generated number in **_"Random Counter".  _**
Link to see how things are working -(https://codesandbox.io/s/useref-react-hook-552hkb)

Summary
- useRef() hook creates references.
- Calling const reference = useRef(initialValue) with the initial value returns a special object named reference. The reference object has a property current: you can use this property to read the reference value reference.current, or update reference.current = newValue.
- Between the component re-renderings, the value of the reference is persistent.
- Updating a reference, contrary to updating state, doesn't trigger component re-rendering.
- References can also access DOM elements. Assign the reference to ref attribute of the element you'd like to access: <div ref={reference}>Element</div> — and the element is available at reference.current.

**_If you have any questions, leave a comment and I'll do my best to respond.
Give this article a like ❤️ if you found it helpful and follow me for more articles like this._**