How to use the useRef React hook
New Course Coming Soon:
Get Really Good at Git
Find out what the useRef React hook is useful for, and how to work with it!
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/
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my
React Beginner's Handbook
→ Read my full
React Tutorial
on The Valley of Code
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X