useRef 与 DOM
约 250 字小于 1 分钟
布欧-Lewyon
2026-05-15
DOM 引用
import { useRef, useEffect } from 'react'
function AutoFocus() {
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
inputRef.current?.focus() // 挂载后自动聚焦
}, [])
return <input ref={inputRef} placeholder="自动聚焦" />
}保存可变值
useRef 保存的值在组件整个生命周期内不变,更新时不触发重渲染。
function Timer() {
const [count, setCount] = useState(0)
const intervalRef = useRef<number | null>(null)
const start = () => {
intervalRef.current = window.setInterval(() => {
setCount(c => c + 1)
}, 1000)
}
const stop = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
intervalRef.current = null
}
}
// 清除
useEffect(() => () => stop(), [])
return <div>{count} <button onClick={start}>Start</button>
<button onClick={stop}>Stop</button></div>
}useRef vs useState
| 对比 | useRef | useState |
|---|---|---|
| 更新触发渲染 | ❌ | ✅ |
| 跨渲染周期保持 | ✅ | ✅ |
| 适合场景 | DOM 引用、定时器 ID、计数 | UI 数据 |
小结
useRef创建可变引用,.current读写。- DOM 引用:
ref={ref}直接绑定到元素。 - 保存不会变化的值(定时器 ID、前一次值)用 useRef。
- 修改
ref.current不会触发重渲染。
上一节:useEffect 与副作用 下一节:useContext 与跨组件通信
