/

How to Use the useRef React Hook

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React, { useState, useRef } from 'react'

const Counter = () => {
const [count, setCount] = useState(0)
const counterEl = useRef(null)

const increment = () => {
setCount(count + 1)
console.log(counterEl)
}

return (
<>
Count: <span ref={counterEl}>{count}</span>
<button onClick={increment}>+</button>
</>
)
}

ReactDOM.render(<Counter />, document.getElementById('app'))

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:

Tags: React hooks, useRef hook, React development