Hello Friends,
Welcome to this new post. In today’s post, we are going to learn about the React refs. In a nutshell, react refs are a way to reference value or DOM elements in react. You might be thinking that we already have React State so why do we need another way to access the DOM element or work with any value in react, to answer this question we will explore the refs in two parts. In part one we will look into the react refs with value; in the second part, we will look into how to use react refs with DOM elements.
let us get going.
Inside this article:
- Part 1- Using the React Refs with Value
- Benefits of Refs in React
- Part 2- Using the React Refs with DOM elements
- Conclusion
Part 1- Using the React Refs with Value
The react provides us useRef hook which we are use to keep reference of any value/DOM element. To work with value using refs we need below three steps.
Import the useRef hook from React
Call the useRef method with some optional initial value
Access or manipulate the value using the .current property using the referenced variable
Complete Code Example
Let us see this in a complete example
first I have created a ClickCounter component(ClickCounter.tsx) as below
import { useRef } from "react";
export default function ClickCounter() {
const refCounter = useRef(0);
function onClickHandler() {
refCounter.current = refCounter.current + 1;
alert("you clicked " + refCounter.current + " times");
}
return (
<>
<button onClick={onClickHandler}>Click</button>
</>
);
}
and then call the ClickCounter in the App component (App.tsx) which is the root component of my example application as below
import ClickCounter from "./components/ClickCounter";
function App() {
return (
<div>
<h2>my App</h2>
<ClickCounter />
</div>
);
}
export default App;
Here is the output of the same on the browser.
Benefits of Refs in React
The useRef method returns a mutable object. it means we can change the internal state of that object directly and the current property will have an initial passed value if we give it. The react will persist the returned object till the component lifetime which means we can keep and use the updated value till the component is not removed from DOM.
One other important benefit is when we update the Ref value, it does not trigger re-render for the components, unlike React state. This can be useful in the scenario when you want to keep the updated value or update the value but do not want to re-render the component. Let us see this with an example.
In the below code. I have added console.log which will log the given message on the browser console whenever it re-renders.
Let us run the application and see what it prints on the browser console.
This is the first log when the component is rendered on browser
Let us click on the buton and see if we get the rendering message again or not.
I have clicked multiple times but the component is not re-rendered which is pretty good for some scenarios. If you use the React useState for the same senario you should get component re-rendering multiple times, I am leaving this as a question to try and respond back in comments. Let me know what you experienced.
Part 2- Using the React Refs with DOM elements
To use the refs with DOM elements in react you need to follow below three steps
Import the useRef hook from React
Call the useRef method to get the object to reference
Assign the returned object to the dom element using the “ref” property
Complete Code Example
Let us see explore it more using a complete example. I have created a sample component for subscribe for newsLetter. Here is the code for the “Newsletter.tsx” file
import { useRef } from "react";
export default function Newsletter() {
const emailInputRef = useRef<HTMLInputElement>(null);
function onSubmitButtonHandler(event: any) {
event.preventDefault();
let emailValue = emailInputRef.current?.value;
console.log("Email: " + emailValue);
}
return (
<>
<h3>Subscribe</h3>
Email:
<input name="emailInput" type="text" ref={emailInputRef} />
<button type="submit" onClick={onSubmitButtonHandler}>
Subscribe
</button>
</>
);
}
If you notice, We are calling the useref() a little differently in the above code, The reason is we are using react with typescript and if just call useRef() then we may get errors like “is possibly ‘null’.ts(18047)”. You can read more about this error in the stackoverflow post.
The “ref” on the “emailInput” is the reserved property name given by react. We can use this property to reference the element with the object we got when we called “useRef()”. To access the value of the input element we can use the [ref object].current.value.
Then, we are just calling the newsletter component in “App.tsx” as below
import Newsletter from "./components/Newsletter";
function App() {
return (
<div>
<h2>my App</h2>
<Newsletter></Newsletter>
</div>
);
}
export default App;
Once we run this example code we can see the below output
The [ref Object].current reference actual object so we can access any property/method of the referenced dom element. Here is what I mean
I have just updated the above “Newsletter.tsx” code to console log the current element.
Conclusion
The React useRef should be used for the use cases when you just want to access DOM elements, keep some value preserved, and apply some DOM effects. It should not be used for the use cases when you want to modify the DOM element otherwise you may end up with an unexpected bug. You can read more about the useRef hook in the React official blog here.
https://beta.reactjs.org/learn/referencing-values-with-refs
https://beta.reactjs.org/learn/manipulating-the-dom-with-refs
Thanks and Happy Learning :). Please give your valuable feedback and share this post if you liked and learned something from this post.