114
四、為什麼不能直接用 ref,而一定要
1️⃣
2️⃣
一、useRef 是什麼(What)
useRef 是 React 提供的一個 Hook,用來建立一個跨 render 穩定存在的容器物件。
const ref = useRef(initialValue)
// ref = { current: initialValue }
- 真正的值永遠放在
ref.current - 修改
ref.current不會觸發 re-render
二、為什麼需要 useRef(Why)
React function component 每次 render 都會重新執行,
一般變數(let / const)無法跨 render 保留值。
useRef 解決的問題是:
我要記住一個值,但它不屬於 UI 狀態,也不該影響畫面
常見用途:
- 操作 DOM
- 儲存第三方套件 instance
- timer / interval id
- 記錄前一次的值
- flag(是否初始化過)
三、useRef 的核心概念(一定要記住)
useRef 回傳的是「容器(盒子)」
真正的值在ref.current裡
❌ ref 不是值本身
✅ ref.current 才是值
四、為什麼不能直接用 ref,而一定要 .current?
useRef 實際結構
const modalRef = useRef(null)
等價於:
const modalRef = { current: null }
- React 只保證 這個物件本身永遠不變
current可以自由修改,不影響 render
五、React + Bootstrap Modal 的角色分工
資料分類
| 類型 | 用什麼 |
|---|---|
| UI 顯示資料 | useState |
| DOM 存取 | useRef |
| Bootstrap 控制器 | useRef |
六、modalRef 與 modalInstanceRef 分別是什麼?
1️⃣ modalRef.current
<div className="modal" ref={modalRef}></div>
modalRef.current= 實際的 DOM 元素(HTMLDivElement)- 由 React 自動塞入
- 用來交給 Bootstrap 接管
2️⃣ modalInstanceRef.current
modalInstanceRef.current = new Modal(modalRef.current)
modalInstanceRef.current= Bootstrap Modal instance(控制器物件)- 包含
.show()、.hide()、.dispose() - 屬於 imperative 行為,不是 UI state
七、這行程式碼在做什麼?
modalInstanceRef.current = new Modal(modalRef.current)
拆解:
modalRef.current
→ 取得 modal 的 DOMnew Modal(dom)
→ 交給 Bootstrap 建立 Modal 控制器
(處理動畫、backdrop、ESC、focus trap)- 存進
modalInstanceRef.current
→ 之後可重複呼叫.show()/.hide()
八、為什麼 modalInstance 不能用 useState?
❌ 不適合用 useState 的原因:
- instance 改變不影響 UI
- 會造成不必要的 re-render
- 語意錯誤(控制器 ≠ UI 狀態)
❌ 不能用一般變數:
- render 會重置
- 會失去 instance
✅ useRef 剛好符合:
- 跨 render
- 不影響畫面
- 專門給行為用
九、最小實戰範例(概念版)
const modalRef = useRef(null)
const modalInstanceRef = useRef(null)
const openModal = () => {
modalInstanceRef.current = new Modal(modalRef.current)
modalInstanceRef.current.show()
}
const closeModal = () => {
modalInstanceRef.current.hide()
}
十、useRef 是否違反「資料驅動畫面」?
❌ 沒有違反
正確理解是:
資料驅動畫面 → 只適用於 UI state
useRef 管的是:
- 非畫面資料
- imperative 行為
- 與現實世界(DOM / 套件)的橋樑
十一、快速判斷法則(實戰心法)
問自己一句話:
這個值改變,需要讓畫面更新嗎?
- 是 →
useState - 否 →
useRef
十二、終極總結(一句話)
useState 管畫面
useRef 管行為
ref 是地址,ref.current 是內容
探索更多來自 雖然沒準備什麼資料 的內容
訂閱即可透過電子郵件收到最新文章。