103
useRef Hook | useRef vs useState
Hey everyone 👋🏻,
In this article, let us understand the useRef
hook in React.js.
As a very first step, import the
useState
,useRef
anduseEffect
hooks from React.Setup an initial state for
counter
and set this to a value of 0 to begin with.Next let us setup an
identifier
ref using theuseRef
hook and set this to an initial value of null to begin with. We are using a ref here instead of a normal variable because we want theidentifier
ref to persist its value across renders. Also if it changes, it won't cause a re-render of the component.Next setup a
useEffect
hook and here let us setup an interval using thesetInterval
function and here we want to update the value ofcounter
each time after 1 second.We can persist the interval value by setting it to the
current
property of theidentifier
ref as shown below. This we will also use in just a second to clear the interval that gets setup when the component unmounts.So return a function from the
useEffect
and let's name it asclearIdentifier
.So define the
clearIdentifier
function as an arrow function and here we can just call theclearInterval
function passing to it our ref value i.eidentifier.current
. Remember theuseEffect
will only run once after every initial render as we have passed an empty array of dependencies..In our JSX, let us render the
counte
r value and a button which can be used to clear the interval and stop the counter.
import { useState, useRef, useEffect } from "react";
const RefExample = () => {
const [counter, setCounter] = useState(0);
const identifier = useRef(null);
const clearIdentifier = () => clearInterval(identifier.current);
useEffect(() => {
identifier.current = setInterval(() => {
setCounter(previousCounter => previousCounter + 1);
},1000);
return clearIdentifier;
},[]);
return (
<div>
<h1>{counter}</h1>
<button onClick={clearIdentifier}>Stop Counter</button>
</div>
)
}
export default RefExample;
As a very first step, let us import the
useEffect
anduseRef
hooks from React.Setup two refs, one for email and other for password i.e
emailRef
andpasswordRef
and set them to an initial value of empty quotes to begin with.In the JSX that we return, let us setup two input fields inside a form element, one for email and other one for password, and place the created refs on each one of them respectively i.e
emailRef
on the email field andpasswordRef
on the password field.Now on the submission of the form, let us invoke a
handleFormSubmission
method. Here we want to tap the values of email and password from the form fields using the refs. So to access the value of an input field using the refs, we can just say :
<name_of_ref>.current.value
So to access the value for email from the form, we can say emailRef.current.value
and to access the value for the password from the form, we can say passwordRef.current.value
. So let us just log them to the console.
Next let us setup a useEffect
hook and on the initial render, let us just set focus on the email using the emailRef
. So for this, add the following code :
useEffect(() => {
emailRef.current.focus();
},[]);
import { useEffect, useRef } from "react";
const RefExample2 = () => {
const emailRef = useRef('');
const passwordRef = useRef('');
useEffect(() => {
emailRef.current.focus();
},[]);
const handleFormSubmission = event => {
event.preventDefault();
const inputEmail = emailRef.current.value;
const inputPassword = passwordRef.current.value;
console.log(`email : ${inputEmail}`);
console.log(`password : ${inputPassword}`);
}
return (
<form onSubmit={handleFormSubmission}>
<input type="email" name="email" ref={emailRef}/>
<input type="password" name="password" ref={passwordRef} />
<button>Register</button>
</form>
)
}
export default RefExample2;
If you prefer video over article, then check this video where I cover about the useRef
hook with the exact same examples.
📺 VIDEO
Thanks for reading !
👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Follow me on Instagram: https://instagram.com/thenerdydev
👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev
103