useRef和createRef區(qū)別
官網(wǎng)的定義如下:
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
換句人話說 , useRef 在 react hook 中的作用, 正如官網(wǎng)說的, 它像一個變量, 類似于 this , 它就像一個盒子, 你可以存放任何東西. createRef 每次渲染都會返回一個新的引用,而 useRef 每次都會返回相同的引用。
useRef常見的一個使用場景是:
組件初始化時 保存一個初始值,由于其是組件生命周期中始終是同一個引用,所以對于想要執(zhí)行一次的操作,可以通過useRef控制,比如:
const myCComponent:React.FC = () => {
const updateRef = React.useRef(false);
// other operations 后,updateRef.current = true
React.useEffect(() => {
if(!updateRef.current){
// doSomething
}
}, [])
}