DEV Community

Cover image for The Mysterious React hook: useRef()
Aadi
Aadi

Posted on • Updated on

The Mysterious React hook: useRef()

useRef() hook is used to create references (or refs in short) in functional components of React.
Yes, that’s it, you can stop reading now (just kidding).

In this article, I’ll briefly explain what a Ref is, what it can do and how to use it without making it much complex.

As per the definition from Reactjs official docs,

Refs provide a way to access DOM nodes or React elements created in the render method.

This is the best definition anyone can give about refs but let me put it even more simply.

Refs let you target any HTML or React element just like the id attributes.

Though refs are slightly different and more convenient in some cases.

  • Now Let’s see where to assign ref and how does the useRef hook helps us:
    As I said earlier, it works like ids so you can put it in a div element like the ids: <div ref={myTarget} /> but why am I using curly brackets instead of strings like we use while assigning ids to elements: <div id='mytarget' />?
    The reason is self-explanatory, we are passing that myTarget as a variable into the ref. This variable is like a name to that particular div element and will help us target it later. Now you might ask that we haven’t defined any variable named myTarget then what are we passing?
    Well then let’s define that variable but a little trick here. You cannot just define any variable and pass it to ref (like const ref = something) because when we pass a variable to ref, it needs to be created specially just to be used in ref. But how do we create a special variable like that? This is where the hook useRef comes in. We use this hook to create our special variable and also assign it an initial value of null as shown in the image.

  • We have created our ref, time to use it:
    To target our beloved element, we use a property called current which acts like an indicator or a signal that tells us whether our targeted element is painted (or loaded) in the DOM or not. We will add an if else condition in useEffect to check that and then do whatever magic we want.
    There are a bunch of things you can do after targeting an element once the DOM loads like adding some animation to that element or if it is an input element then you can add a property called focus to it and it will focus on that input. This comes handy when you want a user to navigate to a form to fill their names once they visit your website or something else. You can also use many third party libraries in it. Here is an image showing the code for whatever I've explained so far.
    Alt Text

Hope this article helped you understand the use of ref attribute and useRef hook in React. I am leaving some links down here in case you want to explore more.
Happy Coding.

Reactjs docs
CSS-tricks article

Top comments (11)

Collapse
 
gyandeeps profile image
Gyandeep Singh

Good highlight article.
Everywhere people use useRef with DOM examples so much that i started thinking thats useRef should be used when DOM is in the questions. Which is not entirely true as it can be used for other purposes. It took me a while to understand the other side as nobody talks about it.

Collapse
 
exploreraadi profile image
Aadi

Yes and thanks.
My intention was to just introduce any beginner with the concept and then brief some of the use cases. After that they can go and do their research well because they got some idea around it. I couldn't find an extremely basic article so wrote one.
And I checked your article, it's well put🙌

Collapse
 
gsarig profile image
Giorgos Sarigiannidis

Nice! Coincidentally, I needed refs yesterday for the first time, on a WordPress Gutenberg plugin using react-leaflet. Leaflet doesn't allow accessing an existing map element by id, so I had to pass the object in a ref, which worked fine.

Collapse
 
imkleats profile image
Ian Kleats

Had my useRef trial-by-fire back in June for the same reasons =D. It's handy for holding & interacting/controlling class instances that would otherwise persist across & perform their own DOM manipulations outside of the React component lifecycle.

Collapse
 
exploreraadi profile image
Aadi

Wow! Great man and I've used leaflet.js too when I built my first ever web app using JavaScript. It was a location bookmark app.
Hope my article helped you clear things up🙌

Collapse
 
exploreraadi profile image
Aadi • Edited

Thanks for your inputs but I wanted to keep this article extremely simple and give anyone who is new to ref to get some idea and then do their research. Official docs are there for that and I linked them too.

Collapse
 
matthewpardini profile image
Matthew Pardini

Refs can also be used to store variables for use in useEffects when you don’t want that variable to be in the dependency array.

Collapse
 
exploreraadi profile image
Aadi

Wow! Thanks for filling me in. I too have just a decent idea about it but considering the time I wasted on understanding refs, I thought a simple article might save someone else's time.

Collapse
 
asyraf profile image
Amirul Asyraf

Thanks for this simple explanation 😆

Collapse
 
exploreraadi profile image
Aadi

Glad it helped🙌

Collapse
 
exploreraadi profile image
Aadi

Glad you found it helpful Daniel😄