DEV Community

Cover image for The Mysterious React hook: useRef()

The Mysterious React hook: useRef()

Aadi on September 21, 2020

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 kid...
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😄