本文将带大家实现 useRef。
先看下如何使用。
function FunctionComponent() {
let ref = useRef(0)
function handleClick() {
ref.current = ref.current + 1
alert(`You clicked ${ref.current} times!`) // 跟组件渲染(状态)没关系
}
return (
<div className="border">
<button onClick={handleClick}>click</button>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
(<FunctionComponent />) as any
);
实现 useRef
export function useRef<T>(initialValue: T): { current: T } {
const hook = updateWorkInProgressHook();
// 初次渲染
if (currentHook === null) {
hook.memoizedState = { current: initialValue };
}
return hook.memoizedState;
}
useRef 应用
与 useState 相比,修改不会触发页面更新。
很多知名库的源码中都能看到 useRef。
- react-router
- antd4/5 中的 useForm
- ahooks 中的 useInterval(useInterval 也用到了 useCallback)