The useRef hook
may not be as popular as other hooks🪝 such as useState
, useEffect
, useContext
and useReducer
. Due to this, it may not be clear what is the purpose of this hook.
Nonetheless, the useRef hook
can be very useful😃 in certain situations.
React
useRef
hook can be helpful when you need to create mutable variables in your components without causing these components to re-render😯.
In this article, we’ll cover what is useRef Hook in React.
If you don’t have a clear idea of how this hook works?
When do you have to use it?
this article will be beneficial to you😉.
Introduction👍
When building a React app, there are going to be times🤓 when you'll want to reference a particular part of the DOM for one reason or another. If you've written Javascript code before, you're likely very familiar with how you would go about doing this, however, In React you'll have to change your ways a bit🤏 — luckily it is pretty painless — in comes the useRef hook
.
The useRef hook is new in React 16.8.
The
useRef hook
is a hook that allows you to directly create a reference to the DOM element in the functional component.
What is useRef Hook🤔
Sometimes, we need to hold a reference to an element or a component that renders in a react component. We can use the useRef hook
in this context.
useRef hook creates a reference pointer to a DOM to allow us to manipulate the element in the situation when logic requires it.
Usually, we will use a change in a state variable to trigger other hooks or to change the state of the UI element. However, there may be some times when we want to trigger a change without having a state. Hence, the useRef hook
can be useful in such a situation.
As told above, useRef
is a hook introduced with other hooks in React version 16.8 and is mainly used for creating a reference of the DOM element or directly accessing it inside a functional component😯.
But don't think even for a second that it's the only thing this hook is capable of🤫 as it can even be used for storing mutable values across different rerenders of the component
.
How It Works🤔
The useRef
hook simply returns an object with a ".current" property which will be the DOM element or value that you plan to use at some point or another within your component.
Note:
useRef
will not cause any re-renders, it is simply an object that holds the DOM or value you've assigned to it😌.
Like every other hook in React, we have to first import this hook at the very top level
as per the rules of hooks and then only we can use it in our apps.
import { useRef } from "react";
const reference = useRef("initial value");
Working With Example😀
Now, let's see how to use useRef()
in practice.
Use case: logging button clicks
The component LogButtonClicks
uses a reference to store the number of clicks on a button:
import { useRef } from "react";
export default function LogButtonClicks() {
const countRef = useRef(0);
const handle = () => {
countRef.current++;
console.log(`Clicked ${countRef.current} times`);
};
console.log("I rendered!");
return <button onClick={handle}>Click me</button>;
}
const
countRef = useRef(0)
creates a referencecountRef
initialized with 0.When the button is clicked, the handle function is invoked and the reference value is
incremented: countRef.current++
. The reference value is logged into the console.Updating the reference value
countRef.current++
doesn't trigger component re-rendering. This is demonstrated by the fact that'I rendered!'
is logged to the console just once, at initial rendering, andno re-rendering
happens when the reference is updated.
Now a reasonable question: what's the main difference between references and state?🤔
Reference and state difference💢
Let's reuse the component LogButtonClicks
from the above section, but this time use useState() hook
to count the number of button clicks:
import { useState } from "react";
export default function LogButtonClicks() {
const [count, setCount] = useState(0);
const handle = () => {
const updatedCount = count + 1;
console.log(`Clicked ${updatedCount} times`);
setCount(updatedCount);
};
console.log("I rendered!");
return <button onClick={handle}>Click me</button>;
}
- Each time you click, you will see in the console the message
'I rendered!'
— meaning that each time the state is updated, the component re-renders.
So, the 2✌️ main differences between references and state:
- Updating a reference doesn't trigger
re-rendering
, while updating the state makes the component re-render. - The reference update is synchronous (the updated reference value is available right away), while the state update is asynchronous (the state variable is updated after re-rendering).
From a higher point of view, references store infrastructure data of side-effects
, while the state stores information that is directly rendered on the screen🤠.
Conclusion🙆♀️
The useRef hook
, as you may see, allows performing complex actions in our component to improve the performance and interactivity of our application.
I hope you have found this article useful.
Thanks for reading it🤗.