How to use the useRef React hook
Find out what the useRef React hook is useful for, and how to work with it!
THE SOLOPRENEUR MASTERCLASS
Now open with 50% OFF launch discount!
Check out my React hooks introduction first, if you’re new to them.
One React hook I sometimes use is useRef
.
import React, { useRef } from 'react'
This hook allows us to access a DOM element imperatively.
Here’s an example, where I log to the console the value of the DOM reference of the 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'))
Notice the const counterEl = useRef(null)
line, and the <span ref={counterEl}>{count}</span>
. This is what sets the link.
Now we can access the DOM reference by accessing counterEl.current
.
See it on Codepen: https://codepen.io/flaviocopes/pen/orENKo/
→ Get my React Beginner's Handbook
I wrote 20 books to help you become a better developer:
- Astro Handbook
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- CSS Handbook
- Node.js Handbook