AI Workshop: learn to build apps with AI →
React Hooks: How to use the useRef React hook

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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/

Lessons in this unit:

0: Introduction
1: Introduction to React Hooks
2: How to use the useState React hook
3: useEffect React hook, how to use
4: How to use the useContext React hook
5: How to use the useReducer React hook
6: How to use the useCallback React hook
7: How to use the useMemo React hook
8: ▶︎ How to use the useRef React hook
9: Can I use React hooks inside a conditional?
10: Why does useEffect run two times?
11: Using useState with an object: how to update
12: How to reference a DOM element in React