慣性聚合 高效追蹤和閱讀你感興趣的部落格、新聞、科技資訊
閱讀原文 在慣性聚合中打開

推薦訂閱源

Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
WordPress大学
WordPress大学
雷峰网
雷峰网
博客园_首页
L
LangChain Blog
Blog — PlanetScale
Blog — PlanetScale
Last Week in AI
Last Week in AI
博客园 - Franky
M
MIT News - Artificial intelligence
S
SegmentFault 最新的问题
博客园 - 【当耐特】
Jina AI
Jina AI
腾讯CDC
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
宝玉的分享
宝玉的分享
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
useRef 在 React 中的隱藏力量
Hariharan S · 2026-05-20 · via DEV Community

1. 介紹

當學習 React Hooks 時,大多數開發者會立即專注於 useState 和 useEffect 這些 Hooks。雖然這些 Hooks 非常重要,但另外一個強大的 Hooks — useRef,卻常常被忽略。

乍看之下,useRef 可能會讓人感到困惑,因為與 useState 不同,更新 useRef 的值不會重新渲染組件。但一旦你了解它是如何工作的,你會發現 useRef 是用於處理 DOM 互動、存儲可變值以及提高 React 應用程式性能的最有用 Hooks 之一。

useRef Hook 允許開發者:

  • 直接存取 DOM 元素

  • 專注輸入欄位

  • 在渲染之間儲存值

  • 管理計時器和間隔

  • 避免不必要的重新渲染

在現代 React 應用程式中,useRef 通常在背景中用於表單處理、視頻控制、滾動追蹤和性能優化等。

在本篇部落格中,我們將探討 useRef 的實際用途、它是如何運作
內部,並在實際的 React 專案中使用,並提供實際範例和對初學者友善的解釋.

2. useRef 在 React 中是什麼?

useRef 是一個 React Hook,讓你參考不需要用於渲染的值.

簡單來說,useRef 提供了你以下的方法:

  • 直接存取 DOM 元素

  • 儲存可變值

  • 保留渲染之間的值

與useState不同,更新useRef的值不會重新渲染組件

3.為何需要useRef?

有時在React中,我們需要:

  • 聚焦輸入欄位

  • 直接訪問按鈕

  • 儲存計時器ID

  • 記住先前值

  • 與DOM元素互動

這裡就是useRef變得有用的地方.

把useRef想像成一個特殊的儲存盒,React會在渲染之間記住它.

4(Syntax of useRef)

const ref = useRef(initialValue);

Enter fullscreen mode Exit fullscreen mode

範例:

const inputRef = useRef(null);

Enter fullscreen mode Exit fullscreen mode

這裡:

  • inputRef → 參考物件

  • null → 初始值

5. 理解如何使用useRef

useRef 回傳一個像這樣的物件:

{
  current: value
}

Enter fullscreen mode Exit fullscreen mode

範例:

const myRef = useRef(0);

console.log(myRef);

Enter fullscreen mode Exit fullscreen mode

輸出:

{
  current: 0
}

進入全螢幕模式 離開全螢幕模式

實際值儲存於內部:

myRef.current

進入全螢幕模式 離開全螢幕模式

6.透過useRef存取DOM元素

其中一種最常見的應用場景.

範例:

import { useRef } from "react";

function App() {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />

      <button onClick={focusInput}>
        Focus Input
      </button>
    </div>
  );
}

進入全螢幕模式 離開全螢幕模式

此功能運作方式:

  1. inputRef 連接到輸入元素

  2. React 將 DOM 元素儲存於 inputRef.current

  3. 當按鈕被點擊時:

inputRef.current.focus()

進入全螢幕模式 退出全螢幕模式

  • 輸入欄位獲得焦點

7.useRef vs useState

這是最重要的概念之一。

useState useRef
會導致重新渲染 不會導致重新渲染
用於UI更新 用於儲存可變值
更新可見數據 靜靜地儲存值

8.示例差異

使用useState:

const [count, setCount] = useState(0);

全屏模式 退出全螢幕模式

更改狀態會更新UI

使用useRef:

const countRef = useRef(0);

進入全螢幕模式 退出全螢幕模式

更改:

countRef.current++;

進入全螢幕模式 退出全螢幕模式

不會重新渲染組件.

9.用useRef儲存先前值

useRef 很有用於記住舊值.

範例:

import { useEffect, useRef, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const previousCount = useRef();

  useEffect(() => {
    previousCount.current = count;
  }, [count]);

  return (
    <div>
      <h1>Current: {count}</h1>
      <h2>Previous: {previousCount.current}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

進入全螢幕模式 退出全螢幕模式

這裡:

  • count 存儲當前值

  • previousCount.current 存儲舊值

10. useRef 的實際應用場景

你通常會用 useRef 來:

  • 專注輸入欄位

  • 存取DOM元素

  • 管理計時器

  • 儲存先前值

  • 防止不必要的重新渲染

  • 影音控制

  • 捲動位置追蹤

11.簡單類比理解useRef

將useRef想像成組件內的一本隱藏筆記本。

React 會記住渲染之間的筆記本,但更改筆記本不會更新螢幕.

範例:

useState  → updates UI
useRef    → stores values silently

進入全螢幕模式 離開全螢幕模式

12.最終心得

useRef 是一個強大的 Hook,允許 React 開發者直接訪問 DOM 元素並存儲可變值,而無需引起不必要的重新渲染。

雖然useState用於更新UI,useRef主要用於在背景儲存值並高效地與DOM互動.

了解何時使用useRef而不是useState是成為更好React開發者的關鍵一步,因為它有助於提高性能和代碼組織。