How to Use the useRef Hook in React
Accessing DOM elements and keeping values between renders with useRef.
When building React components there are times when you need to reach the DOM
directly, like focusing an input when a page loads. Other times you need to hold
on to a value between renders without showing it on screen, like a timer id.
useRef handles both.
useRef returns an object with a current property that stays the same for
the whole life of the component.
Accessing a DOM Element
Create a ref, pass it to an element's ref prop and React will put the DOM node
on ref.current:
import React, { useRef, useEffect } from "react"function SearchInput() {const inputRef = useRef(null)useEffect(() => {inputRef.current.focus()}, [])return <input ref={inputRef} type="search" placeholder="Search" />}
inputRef.current is null during the first render, since the input doesn't
exsist yet. That's why the focus call goes inside
useEffect, which runs after the input is on the page.
The same idea works from an event handler:
function CommentBox() {const textareaRef = useRef(null)return (<div><textarea ref={textareaRef} /><button onClick={() => textareaRef.current.focus()}>Reply</button></div>)}
Keeping a Value Without Re-rendering
Changing ref.current doesn't re-render the component. That makes a ref the
right place for values your code needs but the screen doesn't, like an interval
id:
import React, { useState, useRef } from "react"function Stopwatch() {const [seconds, setSeconds] = useState(0)const intervalRef = useRef(null)const start = () => {if (intervalRef.current) return // already runningintervalRef.current = setInterval(() => {setSeconds((s) => s + 1)}, 1000)}const stop = () => {clearInterval(intervalRef.current)intervalRef.current = null}return (<div><p>{seconds}s</p><button onClick={start}>Start</button><button onClick={stop}>Stop</button></div>)}
seconds is shown on screen, so it's kept in useState. The interval id is
only needed by start and stop, so it goes in a ref. A plain variable
wouldn't work here, since it would reset to its starting value on every render.
useRef vs useState
useState: changing it re-renders the component. Use it for anything shown on screen.useRef: changing it doesn't re-render. Use it for DOM elements and values like timer ids.
If a value shows up in your JSX, it belongs in state. If it doesn't, a ref is usually the simpler choice.
Have some feedback on this post? .