A React ref is a persistent mutable object whose current property stores a value across component renders. Changing current does not trigger a re-render, making refs useful for values that support application mechanics rather than directly updating the interface. section 5.0 section 5.1.2
Use refs when a value must persist but should not independently update the UI:
- Call useRef(initialValue) to receive an object with a current property; React returns the same ref object on each render. section 5.1.2 section 5.4
- Assign ref.current to update stored values without causing a re-render; later renders can read the updated value. section 5.1.1 section 5.1.2
- Store timer IDs in a ref so an event handler or effect cleanup can cancel the timer without adding timer bookkeeping to rendered state. section 5.2
- Attach a ref to a JSX element to let React place the DOM element in current, then call its properties or methods directly. section 5.3 section 5.3.1
Comparing state and ref updates
const [count, setCount] = useState(1);\nconst ref = useRef(1);\n\nconst incCount = () => setCount(c => c + 1);\nconst incRef = () => ref.current++;\n\nThe count button re-renders immediately. The ref button changes ref.current invisibly until another render reveals its latest value. section 5.1.1
Reading an uncontrolled input
const textboxRef = useRef();\n\nfunction goToDate() {\n dispatch({ type: "SET_DATE", payload: textboxRef.current.value });\n}\n\n<input ref={textboxRef} />\n\nThe DOM holds the text while the user types; the handler reads it when Go is clicked. section 5.3.2
Listing 5.1 Comparing useState and useRef when updating state
import React, { useRef, useState } from "react";
function Counter() {
const [count, setCount] = useState(1); #1
const ref = useRef(1); #2
const incCount = () => setCount(c => c + 1); #3
const incRef = () => ref.current++; #4
return (
<div className="App">
<button onClick={incCount}>count: {count}</button> #5
<hr />
<button onClick={incRef}>ref.current: {ref.current}</button> #6
</div>
);
}
#1 Initialize the count value with useState.
#2 Initialize the ref value with useRef.
#3 Define a handler that calls setCount to increment count.
#4 Define a handler that updates the “current” property of the ref.
#5 Call the handler for the count value.
#6 Call the handler for the ref value.
Compare useState and useRef in a focused Counter listing, including handlers and rendered values. section 5.1.1


