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:
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:
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:
- React useRef hook by Flavio Copes (@flaviocopes) on CodePen.
Tags: React hooks, useRef hook, React development