useRef 返回一个可变容器 { current: ... },它在 render 之间保持,但至关重要的是,改变它不会触发 re-render。两个不同的用途:
1. 访问 DOM 节点
jsx
function SearchBox() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // imperatively focus the input on mount
}, []);
return <input ref={inputRef} />;
}
2. 在 render 之间保存可变值
使用它来记住某些内容而不会导致 render——timer ids、prop 的先前值、库的实例:
jsx
function Timer() {
const intervalId = useRef(null);
const start = () => {
intervalId.current = setInterval(tick, 1000); // store across renders
};
const stop = () => clearInterval(intervalId.current);
}
为什么这很重要
jsx
const countRef = useRef(0);
countRef.current++; // changes the value, but the UI does NOT update
const [count, setCount] = useState(0);
setCount(count + 1); // changes value AND re-renders
所以规则是:如果 UI 应该反映该值,请使用 state;如果它只是"幕后"数据,请使用 ref。不建议在 render 期间读取/写入 ref.current(在 effects/handlers 中进行),因为 ref 不被 React 的 render 周期跟踪。
