How to Use the useRef React Hook
Discover the practical uses of the useRef React hook and learn how to effectively use it in your projects!
If you’re new to React hooks, make sure to check out my React hooks introduction first.
One of the useful React hooks that I frequently use is useRef
. It provides a way to access DOM elements imperatively.
To start using the useRef
hook, import it along with React:
1 | import React, { useRef } from 'react' |
Let’s take an example where we log the value of a DOM reference of a <span>
element that contains the count value:
1 | import React, { useState, useRef } from 'react' |
In the above example, pay attention to the line const counterEl = useRef(null)
and the <span ref={counterEl}>{count}</span>
. These lines establish the connection.
Now, by accessing counterEl.current
, we can access the DOM reference.
You can also view and run this example on Codepen:
- React useRef hook by Flavio Copes (@flaviocopes) on CodePen.
Tags: React hooks, useRef hook, React development