Skip to main content

Command Palette

Search for a command to run...

React: Hooks - useRef

Published
1 min read

useRef 可以直接用來 修改DOM節點屬性儲存可變值(mutable value);更棒的是,使用 useRef 不僅會hold住參照值,也不會造成額外的render。


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 的常用時機:(1) 直接存取DOM節點(<Focus/>); (2) 儲存可變值 (<ClassTimer/> vs <HookTimer/>)。

在儲存可變值的範例中,使用Function component 遇到的問題是,當變數是在 useEffect 裡宣告,就沒辦法在函數以外存取這個值,這時可以使用 useRef 來解決這個問題,另外還能在每次 state 改變,也就是 timer 改變造成rerender時保存值。

另外也推薦一位YT工程師James五分鐘解釋useRef和useState的短片也把useRef和useState差異講的非常好。

最後整理一下使用 useRef 的優點:

  1. 可儲存參照值(類似class component的instance properties)
  2. 參照值改變不會有額外的re-render
  3. 即使其他state變數改變 rerender component,還是能儲存參照值

References

2 views

More from this blog

Vite: vite-plugin-html的bugs和坑

因為工作要用Vite去生成一個mpa專案且根據頁面不同,動態生成不同 <title> 的HTML,所以就找了一個套件──vite-plugin-html,結果因為套件好像很久沒維護,隨著Vite升級又多了一些有的沒的bug,順手來記錄一下。 template delete 像我第一個就是遇到生成的時候template HTML也會被刪掉,後來看到issue上也有人反映,還好有好心人士解決這個問題,

Feb 26, 20261 min read4

Lun's Blog

82 posts

Notes for web development